how to decipher this code ?

tangara

Member
Joined
Feb 5, 2016
Messages
6
Programming Experience
1-3
Hi guys,

I am back again with a new question cos I really can't figure out why...
    class Program
    {
        // changing the first letter of each word to Capital letter
        static void Main(string[] args)
        {

            string s = "institute of web technologies science";
            StringBuilder sb = new StringBuilder(s.Length);
            bool capitalize = true;
            foreach (Char c in s)
            {
                sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));// note Char and char is the same
                capitalize = !Char.IsLetter(c); // ???
            }
            sb.ToString();
            Console.Write(sb);
        }
    }
}

From the code I can't tell which line makes the first letter of the words Capital. It's been many days already but I just duno.....:bi_polo:

And also the below line of code, I thought it says it will not capitalize if the letter is found in the string s ?
capitalize = !Char.IsLetter(c); // ???

Hope someone can tell me how to decipher....million thanks.
 
Last edited by a moderator:
The loop goes through the characters in the string one by one. This line:
sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
says to get the upper case version of the current character if `capitalize` is `true` and the lower case version otherwise and append it to the final text. This line:
capitalize = !Char.IsLetter(c);
says that the `capitalize` flag should be set to `true` if the current character is not a letter and `false` otherwise. Together, that means that each character that follows a letter will be lower case while all characters that follow a non-letter will be upper case. The first character in the string will also be upper case if its a letter.
 
Back
Top Bottom