C# c语言中字符位置的获取

C# c语言中字符位置的获取,c#,string,C#,String,我使用下面的代码来获得E的位置 上述代码将返回位置=5 我是C新手,我的问题是没有循环的任何快速方法都可以做到这一点,您可以使用: 它返回字符或子字符串的第一个索引,如果不存在,则返回-1。使用 单次/首次出现 使用IndexOf将返回位置的索引 using System; class Program { static void Main() { // A. // The input string. const string s = "ABCD

我使用下面的代码来获得E的位置

上述代码将返回位置=5

我是C新手,我的问题是没有循环的任何快速方法都可以做到这一点,

您可以使用:

它返回字符或子字符串的第一个索引,如果不存在,则返回-1。

使用

单次/首次出现 使用IndexOf将返回位置的索引

using System;

class Program
{
    static void Main()
    {
    // A.
    // The input string.
    const string s = "ABCDEFGHIJKLM";

    // B.
    // Test with IndexOf.
    if (int i = s.IndexOf("E") != -1)
    {
        Console.Write("string contains 'E' at position of "+i);
    }
    Console.ReadLine();
    }
}
这将输出

字符串在位置4处包含“E”

为了快速/更好地理解:

你可以学到更多 或 indexOf获取字符的位置,否则将返回-1

多次出现: 如果char值在整个字符串中多次出现,则可以使用:

 var foundIndexes = new List<int>();

 for (int i = 0; i < myStr.Length; i++)

     if (myStr[i] == 'a') foundIndexes.Add(i);

发现

奇怪的是,副本有一个相似的字符串,相同的字符,甚至相同的OP。从那以后,你没有学到很多东西,是吗?1k代表,但没有搜索努力,10个月前发布了相同的问题。。。哥们儿可不是这样的…@xmashallax:OP自己也问过这个问题。真有趣。所以他只能在他的记忆中寻找。哦,对了。。。更令人失望的是…智商水平不会被这个问题测试。
int position = mystring.IndexOf("E");
using System;

class Program
{
    static void Main()
    {
    // A.
    // The input string.
    const string s = "ABCDEFGHIJKLM";

    // B.
    // Test with IndexOf.
    if (int i = s.IndexOf("E") != -1)
    {
        Console.Write("string contains 'E' at position of "+i);
    }
    Console.ReadLine();
    }
}
 var foundIndexes = new List<int>();

 for (int i = 0; i < myStr.Length; i++)

     if (myStr[i] == 'a') foundIndexes.Add(i);