0

编辑:所以事实证明我之前的内容是正确的,我只是将索引数错了。谢谢你的意见。

使用一种方法来查找用户给定字符串中的所有子字符串索引。我在从 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);但我不完全确定如何在保持子字符串位置的准确记录的同时设置新的起始位置。

4

3 回答 3

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");
于 2013-10-25T18:08:05.803 回答
4

使用 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.

于 2013-10-25T18:36:07.233 回答
1

你这里还有一个问题。假设您致电:

getSubStringPositions("abcabcabcabc", "abcabc");

您的函数将错误地报告字符串出现两次,而实际上子字符串出现了 3 次,如下所示:

  • abcabc.abcabc
  • abc.abcabc.abc <-- 你的函数跳过这个
  • abcabc.abcabc。
于 2013-10-25T18:32:43.223 回答