Search code examples
c#string-formattingindexofcapitalizetoupper

How do I make letters to uppercase after each of a set of specific characters


I have a collection of characters (',', '.', '/', '-', ' ') then I have a collection of strings (about 500).

What I want to do as fast as possible is: after each of the characters I want to make the next letter uppercase.

I want the first capitalized as well and many of the strings are all uppercase to begin with.

EDIT: I modified tdragons answer to this final result:

    public static String CapitalizeAndStuff(string startingString)
    {
        startingString = startingString.ToLower();
        char[] chars = new[] { '-', ',', '/', ' ', '.'};
        StringBuilder result = new StringBuilder(startingString.Length);
        bool makeUpper = true;
        foreach (var c in startingString)
        {
            if (makeUpper)
            {
                result.Append(Char.ToUpper(c));
                makeUpper = false;
            }
            else
            {
                result.Append(c);
            }
            if (chars.Contains(c))
            {
                makeUpper = true;
            }
        }
        return result.ToString();
    }

Then I call this method for all my strings.


Solution

  • string a = "fef-aw-fase-fes-fes,fes-,fse--sgr";
    char[] chars = new[] { '-', ',' };
    StringBuilder result = new StringBuilder(a.Length);
    bool makeUpper = true;
    foreach (var c in a)
    {
        if (makeUpper)
        {
            result.Append(Char.ToUpper(c));
            makeUpper = false;
        }
        else
        {
            result.Append(c);
        }
        if (chars.Contains(c))
        {
            makeUpper = true;
        }
    }