相当于Java的charAt()的C#吗?


118

我知道我们可以使用charAt()Java中的方法通过指定其位置来获取字符串中的单个字符。C#中有等效的方法吗?


您是否正在寻找仅适用于保证不包含任何非16位Unicode字符的字符串的解决方案?还是在寻找适用于任意字符串的解决方案?
hippietrail 2015年

Answers:


201

您可以像数组一样索引C#中的字符串,然后在该索引处获取字符。

例:

在Java中,您会说

str.charAt(8);

在C#中,您会说

str[8];

2
我认为应该指出,str.Substring(8,1)可作为一种解决方案,但速度要慢得多。刚发现很难。
qzcx

这挽救了我的生命:D非常感谢!
Spidi's Web



-1

请尝试使其成为一个角色

string str = "Tigger";
//then str[0] will return 'T' not "T"

-2

Console.WriteLine允许用户在字符串中指定位置。

查看示例:

字符串str =“ Tigger”; Console.WriteLine(str [0]); //返回“ T”;Console.WriteLine(str [2]); //返回“ g”;

你去!


-3

只需使用String.ElementAt()。它与java的非常相似String.charAt()。祝您编码愉快!


当您可以做很多年前其他人提到的事情时,为什么还要使用IEnumerable扩展方法?(内置字符串索引)。
Dave Doknjas,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.