Search code examples
c#stringtoupper

How do I capitalize every third character in my code C#?


I'm learning about C# but there is something that's frustrating me. I was learning about strings methods and how they work.

public static void CaseFlip()
        {
            Console.WriteLine("             CaseFlip -- Output");
            Console.WriteLine("==============================================================================");


           for (int i = 0; i < text.Length; i ++)
           {
            char[]delimiters = {'/'};
            string[]splitString = text.Split(delimiters);


                for (int k  = 0; k < splitString.Length; k +=3)
                    {
                    string sub = text.Substring(0);
                    string remove = sub.Remove(4, text.Length);
                    string insert = remove.Insert(0, sub);

                    splitString[k] = splitString[k].ToUpper();
                    Console.WriteLine(splitString[k]);
                    }
           }
           Console.WriteLine(" ");

        }

and my string array is:

static string text = "You only have one chance to make a first impression/" +
        "Consider the source and judge accordingly/" +
        "You can do something for a day you can't imagine doing for a lifetime/" +
        "Are we not drawn onward, we few, drawn onward to new era/" +
        "Never odd or even/" +
        "Madam, I'm Adam/" +
        "What do you mean? It's not due tomorrow, is it?";

What to do?


Solution

  • You can use Substring to select the character you want to convert to upper case, and then use Remove to remove that original character from the string, and Insert to add the uppercase character back in. Because strings are immutable, you also need to store the intermediate steps in a variable to have the changes carry over to the next cycle.

    public static void CaseFlip()
    {
        Console.WriteLine("             CaseFlip -- Output");
        Console.WriteLine("==============================================================================");
    
        var splitString = text.Split('/');
        for (var i = 0; i < splitString.Length; i++)
        {
            var line = splitString[i];
            for (var k = 0; k < line.Length; k += 3)
            {
                var upperCasedCharacter = line.Substring(k, 1).ToUpper();
                line = line.Remove(k, 1).Insert(k, upperCasedCharacter);
            }
    
            Console.WriteLine(line);
        }
    
        Console.WriteLine(" ");
    }