How can I get a character in a string by index?

C#.NetStringIndexof

C# Problem Overview


I know that I can return the index of a particular character of a string with the indexof() function, but how can I return the character at a particular index?

C# Solutions


Solution 1 - C#

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Solution 2 - C#

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSmartestVEGAView Question on Stackoverflow
Solution 1 - C#Tim RobinsonView Answer on Stackoverflow
Solution 2 - C#Brian RasmussenView Answer on Stackoverflow