我正面临着解决这个问题的问题。例如,我有一个字符串变量
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()
。谁能帮我做这个?
最佳答案
The problem is we cant use built in string class methods 'contains()','lastIndexOf()'. can anyone help me to do this?
然后您可以构建自己的。我假设甚至 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
关于c# - 在 C# 中查找匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11243207/