在不使用任何内置函数的情况下检查 c# 中的另一个字符串中是否存在一个单词

Check if a word exists in another string in c# without using any inbuilt function

string sentence = "This is a goodday";
string word = "good";

我知道这可以用 .Contains() 方法来完成。我在采访中被问到如何在没有 contains 方法的情况下做到这一点。

使用 for 循环怎么样? 循环检查作品的第一个字符的句子。一旦找到,检查单词的下一个字符,直到找到整个单词(完成 - 单词存在于句子中)或不同的字符,然后重新开始寻找单词的第一个字符,直到 运行 出来字符数。

正如评论所说,让我们知道您的回答会更好。

试试这个:

    static bool checkString(string inputString="",string word="")
    {      
            bool returV=false;            
            if(inputString =="" ||  word=="")
                return false;
            int intexcS=0;    
            Dictionary<int,string> d = new Dictionary<int, string>();
            foreach (char cW in word)
            {
                foreach (char cS in inputString)
                {                      
                    if(cW==cS){                        
                        if(!d.ContainsKey(intexcS) && d.Count<word.Length){
                            d.Add(intexcS,cW.ToString());  
                        }
                    }
                intexcS++;
                }
                intexcS=0;
            }
            int i=0;
            foreach(var iitem in d) { if(iitem.Value!=word[i].ToString()) returV=false; else returV=true; i++;  }
            return returV;
    }

如何用英语完成。

pick the first letter of word.
walk down sentence a character at a time till you find that letter
now look at the next letters in sentence to see if they are the rest of that word
yes - done
no - keep going

要使用的是 word[x] 是单词的第 x-1 个字符,所以你只需要 2 个索引和一个循环或 2

Q: 在不使用任何内置函数的情况下检查 c# 中是否存在另一个字符串中的单词
A: 棘手

这取决于“任何内置功能”到底有多详细。

总的来说算法很简单:

Loop through the string you're searching in
    for each position, see if you've found the word

    you do this by looping through all the characters in what we're looking for
        and compare each character from the first string with one from the second
    if they all matched, we've found a match

但是……“不使用任何内置函数”。

假设这意味着,不要使用明显的东西,例如 Contains、IndexOf、正则表达式,所有这些东西。

但是走极端,这是否意味着我连字符串有多长都不知道? s.Length 是一个 built-in 函数吗?因此不允许?

public bool Contains(string value, string whatWereLookingFor)
{
    return IndexOf(value, whatWereLookingFor) >= 0;
}

public int Length(string s)
{
    int result = 0;
    for (int i = 0; i <= 2147483647; i++)
    {
        try
        {
            char c = s[i];
        }
        catch (IndexOutOfRangeException)
        {
            break;
        }
        result = i + 1;
    }
    
    return result;
}

public int IndexOf(string value, string whatWereLookingFor)
{
    int iMax = Length(value);
    int whatMax = Length(whatWereLookingFor);
    for (int i = 0; i <= iMax - whatMax; i++)
    {
        bool isMatch = true;
        for (int j = 0; j < whatMax; j++)
        {
            if (value[i + j] != whatWereLookingFor[j])
            {
                isMatch = false;
                break;
            }
        }
        if (isMatch)
            return i;
    }
    return -1;
}