[英]Find matching word in C#
我遇到了解决这个问题的问题。 我有一个字符串变量,例如
string text="ABCD,ABCDABCD,ADCDS";
我需要在上面的字符串中搜索像'BC'这样的字符串值,并找到“BC”出现的位置。 即如果我们将“BC”搜索到该字符串变量,它将输出为1,6
0 1 2 3 4 5 6 7 8 9 10 11 12 13
-------------------------------------------------------
| A | B | C | D | , | A | B | C | D | , | A | D | C | S |
-------------------------------------------------------
问题是我们无法使用内置的字符串类方法contains()
, lastIndexOf()
。 任何人都可以帮我这样做吗?
问题是我们不能使用内置的字符串类方法'contains()','lastIndexOf()'。 任何人都可以帮我这样做吗?
然后你可以建立自己的。 我假设甚至禁止使用Substring
。
string text="ABCD,ABCDABCD,ADCDS";
string whatToFind = "BC";
List<int> result = new List<int>();
for(int index=0; index < text.Length; index++)
{
if(index + whatToFind.Length > text.Length)
break;
bool matches = true;
for(int index2=0; index2<whatToFind.Length; index2++)
{
matches = text[index+index2] == whatToFind[index2];
if(!matches)
break;
}
if(matches)
result.Add(index);
}
这是运行代码: http : //ideone.com/s7ej3
这应该适合你:
string text="ABCD,ABCDABCD,ADCDS";
var seekindex = 0;
var positions = new List<int>();
while( seekindex < text.Length ){
var index = text.IndexOf( "BC", seekindex);
if( index > -1){
positions.Add(index);
seekindex = index + 1;
}else{
break;
}
}
这使用带有startindex的IndexOf
方法来确保我们下次继续从我们之前的命中位置搜索,并且直到IndexOf
返回-1表示不再有命中。
positions
将包含最后的索引,结果实际上是1,6,10而不是1,6;)
编辑
刚刚意识到他无法使用IndexOf
。 再试一次:)
string text="ABCD,ABCDABCD,ADCDS";
var positions = new List<int>();
for( int i = 0; i < text.Length-1; i++ ){
if( text[i] == 'B' && text[i+1] == 'C' ){
positions.Add(i);
}
}
这似乎是一个性能问题,因为if语句检查当前和下一个字符,因此检查所有字符两次。
但事实上它不会。 由于它们之间的AND(&&),如果text[i]
不是B,它将不会执行第二次检查,因为它知道if无论如何都会失败。
string text = "ABCD,ABCDABCD,ADCDS";
int location;
for (int i = 0; i < text.Length; i++)
if (text[i] == 'B')
if (text[i + 1] == 'C')
{
location = i;
i++;
}
编辑:
List<int> locations = new List<int>();
string text = "ABCD,ABCDABCD,ADCDS";
for (int i = 0; i < text.Length; i++)
if (text[i] == 'B')
if (text[i + 1] == 'C')
{
location.Add(i);
i++;
}
可能你不能在作业中使用regural表达。 最好的解决方案是将您的字符串视为char数组。 阅读http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
滚动你自己的IndexOf
版本并不难(根据你已经收到的答案),并且因为它是家庭作业,你可以侥幸逃脱它。
但是,正如您可能想象的那样,简单的for
循环并不是最有效的方法。 字符串搜索是一个重要的主题,虽然您可能不需要再次在作业之外实现它,但您可以阅读它以进行自己的启发。
下面是一个完美的示例,满足您的要求,但也很好,速度慢,内存占用大:
string text = "ABCD,ABCDABCD,ADCDS";
string whatToFind = "BC";
string delim = "";
for(int index=0; index < text.Length; index++)
{
if(index + whatToFind.Length > text.Length)
break;
if(text.SubString(index, whatToFind.Length) == whatToFind)
{
Console.Out.WriteLine(delim + index.ToString())
delim = ",";
}
}
我将它留给读者作为练习来提高性能和内存使用率。 了解速度缓慢的地方和原因比获得更快的答案更有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.