C# - 查找子字符串的所有索引 [英] C# - Finding All Indices of a Substring
问题描述
编辑:所以事实证明我之前所做的是正确的,我只是把索引计算错了。感谢您的输入。
So it turns out what I had before was correct, I was simply counting the indexes wrong. Thank you for your input though.
处理从用户查找给定字符串中所有子字符串索引的方法。我遇到从userString.IndexOf获取正确位置的问题。我知道它发现所有出现的子字符串,但是整数索引大量关闭。
Working on a method that finds all substring indices in a given string from the user. I am having issues with getting correct positions from userString.IndexOf. I know it's finding all occurrences of the substring, but the integer index is off by a substantial amount.
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;
}
我认为这可能是位置+的问题= userString.IndexOf(userSubString,position);
但是我不完全确定在维护子字符串位置的准确记录时如何设置新的起始位置。
I think it may be an issue with position += userString.IndexOf(userSubString, position);
but am not entirely sure how I would go about setting the new start position while maintaing an accurate record of the substring locations.
推荐答案
删除位置前面的+ =
Remove the += in front of position
position = userString.IndexOf(userSubString, position);
此外,您应该更改代码以保存初始找到的位置并将位置变量设置为在上一个
Also you should change your code to save the initial found position and set the position variable to search after the previous one
// 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 类实例进行字符串连接
As a final note, if this search produces many hits it is better to change the string concatenation using a StringBuilder class instance
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");
这篇关于C# - 查找子字符串的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!