Manipulating Strings in C#—Accessing the String's Characters
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Accessing the String's Characters
We learned earlier that you can think of a string as an array of characters. In this chapter you will get a little preview of navigating through character arrays.
To access the characters of a string:
- Type
char c = str[x];wherecis a variable to hold the character from the string,stris the string variable andxis the zero-based position of the character you wish to save (Figure 4.40).
- Type
- Figure 4.40. Because strings are essentially arrays of characters, you can address any character in the array by specifying its zero-based index in square brackets.
Tips
- There are two ways of enumerating through all the characters in a string. One way is to write a loop where you maintain an index with an integer variable. The index begins at zero and increases until the index is equal to
Length–1 (see "Finding the String's Length" earlier in this chapter) (Figure 4.41). The other way is to use a function calledforeach.
- There are two ways of enumerating through all the characters in a string. One way is to write a loop where you maintain an index with an integer variable. The index begins at zero and increases until the index is equal to

- Figure 4.41 This code shows a common way to parse the characters of the string in a loop. It searches for commas to count names.

- Figure 4.42 An easier way to navigate through the characters of the string is to use the
foreachmethod.
- If you ask for an index greater than
Length–1, the string class generates an exception. The exception (or error) isIndexOutOfBoundsException.
- If you ask for an index greater than
- You can access the characters of the string, but you can't modify them since strings are immutable (Figure 4.43).

- Figure 4.43. You can reassign a string variable to another string but you can't really change an existing string.
- If the
IndexOforLastIndexOffunctions don't find any occurrences of the substring, the functions return–1.
- If the
- There are a few variations of the
IndexOfandLastIndexOffunctions. One variation lets you specify a location within the string where you want to start the search. This is useful for cases in which you wish to scan the string for one character, then when you find it, you want to get the next occurrence of the same character. In that case you specify that you want to begin the search in the position after the first occurrence (Figure 4.45).
- There are a few variations of the

- Figure 4.45. Without specifying an index,
IndexOfalways searches from the same character. However, you can specify a starting position, as you can see from the examples above.
|


