我知道可以使用 indexOf()
函数返回字符串中特定字符的索引,但是如何返回特定索引处的字符呢?
string s = "hello";
char c = s[1];
// now c == 'e'
另请参考 Substring
,以返回多个字符。
你的意思是这样吗
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
字符串也实现了 IEnumberable<char>
接口,所以你也可以这样枚举它:
foreach (char c in s)
Console.WriteLine(c);
foreach (string substring in s.Chunk(2)) { ... }
。Enumerable.Chunk 是.NET 6+内置的,你可以在这里找到其他版本的示例实现:https://dev59.com/S2ct5IYBdhLWcg3wD5SU - Heinzi
indexof()
时要使用的字符,为什么还需要从字符串中获取它呢?您可以使用可能的indexof()
来返回该字符并证明其首先存在于字符串中。 - Mike Two