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

前端 未结 2 1187
别那么骄傲
别那么骄傲 2020-11-27 23:08

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?<

相关标签:
2条回答
  • 2020-11-27 23:54

    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);
    
    0 讨论(0)
  • 2020-11-27 23:57
    string s = "hello";
    char c = s[1];
    // now c == 'e'
    

    See also Substring, to return more than one character.

    0 讨论(0)
提交回复
热议问题