Because a character can be accessed by index, a variable loop can be used to iterate over all characters, which will take possible index values. For example, a program that displays all the character codes of the string s would look like this:
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);
Console.WriteLine(Convert.ToInt32(s[i]));
}
Program notes:
1) s.Length
finds the length of a string. The index of the first character is 0 and the index of the last is s.Length-1
. The loop variable i will just take values sequentially from 0 to s.Length
-1
;
2) in each line, the symbol itself will be displayed first, and then its code, which can be obtained through the Convert.ToInt32()
;
method
The same enumeration can be written shorter:
foreach (char c in s)
{
Console.WriteLine(c);
Console.WriteLine(Convert.ToInt32(c));
}
In this snippet, the loop header loops through all s characters, placing one by one into the variable c.
The peculiarity of C# when working with strings is that strings are immutable objects. In other words, we cannot change individual characters of a string.
For example, the following statement will not work:
s[5]=" ";