C# - 查找子字符串的所有索引

时间:2013-10-25 18:05:47

标签: c# string loops indexing indices

编辑:所以事实证明我以前所做的是正确的,我只是把索引计算错了。谢谢你的意见。

处理一个方法,该方法从用户中查找给定字符串中的所有子字符串索引。我遇到从userString.IndexOf获取正确位置的问题。我知道它发现了所有出现的子串,但是整数索引大量关闭。

private static void getSubStringPositions(string userString, string userSubString)
{
    string subStringPositions = "";
    int position = 0;

    if (userString.IndexOf(userSubString, position) == -1)
    {
        Console.WriteLine("Your sub-string was not found in your string.\n");
        return;
    }
    while (position < userString.Length)
    {
        position += userString.IndexOf(userSubString, position);
        subStringPositions += Convert.ToString(position) + ", ";
    }

    Console.WriteLine("The occurernce(s) for your sub-string are: " + subStringPositions + "\n\n");
    return;
}

我认为这可能是position += userString.IndexOf(userSubString, position);的一个问题,但我并不完全确定如何在维护子字符串位置的准确记录时设置新的起始位置。

3 个答案:

答案 0 :(得分:4)

删除位置前面的+ =

   position = userString.IndexOf(userSubString, position);

此外,您应该更改代码以保存初始找到的位置,并将位置变量设置为在上一个位置后搜索

    // Initial check...
    position = userString.IndexOf(userSubString);
    if(position == -1)
    {
        Console.WriteLine("Your sub-string was not found in your string.\n");
        return;
    }
    // Save the found position and enter the loop
    subStringPositions = Convert.ToString(position) + ", ";

    while (position < userString.Length)
    {
        // Search restart from the character after the previous found substring
        position = userString.IndexOf(userSubString, position + 1);
        subStringPositions += Convert.ToString(position) + ", ";
    }

最后请注意,如果此搜索产生许多匹配,最好使用StringBuilder类实例更改字符串连接

    StringBuilder subStringPositions = new StringBuilder();
    subStringPositions.Append(Convert.ToString(position) + ", ");

    while (position < userString.Length)
    {
        // Search restart from the character after the previous found substring
        position = userString.IndexOf(userSubString, position + 1);
        subStringPositions.Append(Convert.ToString(position) + ", ";
    }
    Console.WriteLine("The occurrence(s) for your sub-string are: " + 
                      subStringPositions.ToString() + "\n\n");

答案 1 :(得分:2)

使用LINQ查找这些索引的简明方法:

public static IEnumerable<int> FindIndexes(string text, string query)
{
    return Enumerable.Range(0, text.Length - query.Length)
        .Where(i => query.Equals(text.Substring(i, query.Length));
}

FindIndexes("abcbcbc", "bcb")会找到索引13

答案 2 :(得分:1)

你这里有另一个问题。我们说你打电话:

getSubStringPositions(“abcabcabcabc”,“abcabc”);

你的函数会错误地报告字符串出现两次,实际上子字符串发生了3次,如下所示:

  • abcabc.abcabc
  • abc.abcabc.abc&lt; - 你的函数跳过这一个
  • abcabc.abcabc。