Convert all first letter to upper case, rest lower for each word

Viewed 137990

I have a string of text (about 5-6 words mostly) that I need to convert.

Currently the text looks like:

THIS IS MY TEXT RIGHT NOW

I want to convert it to:

This Is My Text Right Now

I can loop through my collection of strings, but I am not sure how to go about performing this text modification.

11 Answers
string s = "THIS IS MY TEXT RIGHT NOW";

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

There are a couple of ways to go about converting the first character of a string to upper case.

The first way is to create a method that simply caps the first character and appends the rest of the string using a substring:

public string UppercaseFirst(string s)
{
    return char.ToUpper(s[0]) + s.Substring(1);
}

The second way (which is slightly faster) is to split the string into a character array and then rebuild the string:

public string UppercaseFirst(string s)
{
    char[] a = s.ToCharArray();
    a[0] = char.ToUpper(a[0]);
    return new string(a);
}

Untested but something like this should work:

var phrase = "THIS IS MY TEXT RIGHT NOW";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=\w)\w");
var newString = rx.Replace(phrase,new MatchEvaluator(m=>m.Value.ToLowerInvariant()));

Essentially it says "preform a regex match on all occurrences of an alphanumeric character that follows another alphanumeric character and then replace it with a lowercase version of itself"

I don't know if the solution below is more or less efficient than jspcal's answer, but I'm pretty sure it requires less object creation than Jamie's and George's.

string s = "THIS IS MY TEXT RIGHT NOW";
StringBuilder sb = new StringBuilder(s.Length);
bool capitalize = true;
foreach (char c in s) {
    sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
    capitalize = !Char.IsLetter(c);
}
return sb.ToString();

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.

This is one of the possible solutions you might be interested in. Traversing an array of characters from right to left and vice versa in one loop.

public static string WordsToCapitalLetter(string value)
{
    if (string.IsNullOrWhiteSpace(value))
    {
        throw new ArgumentException("value");
    }

    int inputValueCharLength = value.Length;
    var valueAsCharArray = value.ToCharArray();

    int min = 0;
    int max = inputValueCharLength - 1;

    while (max > min)
    {
        char left = value[min];
        char previousLeft = (min == 0) ? left : value[min - 1];

        char right = value[max];
        char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];

        if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
        {
            valueAsCharArray[min] = char.ToUpper(left);
        }

        if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
        {
            valueAsCharArray[max] = char.ToUpper(right);
        }

        min++;
        max--;
    }

    return new string(valueAsCharArray);
}

jspcal's answer as a string extension.

File Program.cs

class Program
{
    static void Main(string[] args)
    {
        var myText = "MYTEXT";
        Console.WriteLine(myText.ToTitleCase()); //Mytext
    }
}

File StringExtensions.cs

using System;
public static class StringExtensions
{

    public static string ToTitleCase(this string str)
    {
        if (str == null)
            return null;

        return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }
}
Related