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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:48:54  来源:igfitidea点击:

How extract a specific character in a string in c# by index

c#string

提问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: xwould be assigned m.

注意:x将被分配m

You can also iterate using a forloop, like this:

您还可以使用for循环进行迭代,如下所示:

char y;
for (int i = 0; i < myString.Length; i ++)
{
    y = myString[i];
}

Finally, you can use the foreachloop 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 nof string s.

在 C# 中也是一样:s[n]让你得到nstring 的字符数s