c# - 在 C# 中查找匹配的单词

标签 c# .net string for-loop

我正面临着解决这个问题的问题。例如,我有一个字符串变量

              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/

相关文章:

c - strtok() 的使用

c# - 设置打印区域 - OpenXML with Excel

c# - 将 SQL 转换为 LINQ 查询

c# - 线程是否在等待锁 FIFO?

.net - 我应该使用哪个 sn.exe?

c# - 匿名类型 VS 局部变量,什么时候应该使用?

c# - 执行异步查询 Azure 表存储的最佳方式

c# - 当我从子门户访问 ashx 时,为什么 DNN 会杀死我的身份验证 cookie?

java - 在 Java 中完美散列三个字母的小写字符串的最佳方法?

c# - Perl 的重复运算符在 C# 中的等效项是什么?