C# Accessing Strings
In C#, you can access individual characters or substrings within a string using indexing and methods like Substring()
. Strings are zero-indexed, meaning the first character is at index 0.
Key Topics
1. Character Access
Example: Accessing Characters by Index
string message = "Hello";
char firstChar = message[0];
Console.WriteLine(firstChar); // Outputs: H
2. Using Substring()
Example: Extracting a Substring
string message = "Hello, World!";
string sub = message.Substring(7, 5);
Console.WriteLine(sub); // Outputs: World
3. Iterating Over a String
Example: Looping Through Each Character
string word = "Hello";
foreach(char c in word)
{
Console.WriteLine(c);
}
Output:
H
e
l
l
o
Key Takeaways
- Use index notation
string[index]
to access characters. - The
Substring()
method extracts parts of a string. - You can iterate over a string using loops.