c#如何通过索引提取字符串中的特定字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18285566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How extract a specific character in a string in c# by index
提问by Mohammad Reza Rezwani
In c++ strings are like array when you write str[i] you can acsess i+1 element of array in there something like that in c# I do not need indexOf method because that is different I need something to bring characters in string by their index
在 c++ 中,字符串就像数组,当你写 str[i] 时,你可以访问数组的 i+1 元素,就像在 c# 中那样,我不需要 indexOf 方法,因为那是不同的,我需要一些东西通过索引将字符带入字符串
采纳答案by Karl Anderson
Yes, you can reference characters of a string using the same syntax as C++, like this:
是的,您可以使用与 C++ 相同的语法来引用字符串的字符,如下所示:
string myString = "dummy";
char x = myString[3];
Note: x
would be assigned m
.
注意:x
将被分配m
。
You can also iterate using a for
loop, like this:
您还可以使用for
循环进行迭代,如下所示:
char y;
for (int i = 0; i < myString.Length; i ++)
{
y = myString[i];
}
Finally, you can use the foreach
loop to get a value already cast to a char
, like this:
最后,您可以使用foreach
循环获取已转换为 a 的值char
,如下所示:
foreach(char z in myString)
{
// z is already a char so you can just use it here, no need to cast
}
回答by RichieHindle
It's just the same in C#: s[n]
gets you character number n
of string s
.
在 C# 中也是一样:s[n]
让你得到n
string 的字符数s
。