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

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

9
  • 4
    And you haven't even made an attempt? Commented Feb 8, 2022 at 8:07
  • 4
    You've been interviewed, not us. So this is primarily your task. So please be so kind to post what you've tried and where specifically you need our help. Not just ship your task to us. Commented Feb 8, 2022 at 8:10
  • First off, read as many MSDN documentation, tutorials and articles as you can on the web. There are a few classes and techniques you should know well cause you will use them often. Other than that, you can achieve this via using IndexOf() or via using advanced Regex. Commented Feb 8, 2022 at 8:16
  • Without using any inbuilt functions, you're basically limited to using either Regex or a recursive function that uses for loops cycling through each character in the string. Commented Feb 8, 2022 at 8:22
  • 1
    @RivoR. IndexOf() wouldn't meet the "No inbuilt functions" rule Commented Feb 8, 2022 at 8:23

6 Answers 6

3

how to do it in english.

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

the thing to use is that word[x] is the x-1th character of word, so you just need 2 indexes and a loop or 2

Sign up to request clarification or add additional context in comments.

Comments

1

Q: Check if a word exists in another string in c# without using any inbuilt function
A: Tricky

It depends on how detailed that "any inbuilt function" really is.

In general the algorithm is simple:

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

but then ... "without using any inbuilt function".

I assume this would mean, do not use the obvious ones, such as Contains, IndexOf, a regular expression, all those things.

But taken to the extreme, does that mean I cannot even know how long the strings are? Is s.Length a built-in function? And thus not allowed?

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;
}

Comments

1

Since we cannot use Contains method from string class, How about this if we loop through the sentence and use Extension Method to Extend string class and implement own custom SubString method to check wether the given word exists in string or not.

string sentence = "This goodday";
string word = "good";
bool flag = false;
for (int i = 0; i < sentence.Length - word.Length; i++)
{
    if (word.Equals(sentence.CustomSubstring(i, word.Length)))
    {
        flag = true;
        break;
    }
}

public static class MyExtendStringClass{
    public static string CustomSubstring(this string sentence, int startIndex, int noOfLetters){
        string result = string.Empty;

        for (int i = startIndex; i < sentence.Length; i++)
        {
            if (noOfLetters != 0)
            {
                result += sentence[i];
                noOfLetters--;
            }
            else
            {
                break;
            }
        }

        return result;
    }
}

2 Comments

"Substring" probably counts as "built-in method"
@HansKesting thanks for correcting me, i have other alternative, Where we can implement our own substring method by Extending string class in this way we can achieve the same result by considering all constraints
0

How about using a for loop? Loop through the sentence checking for the first character of the work. Once you find that check for the next character of the word until you find the whole word (done - word exists in sentence) or a different character so you start again looking for the first character of the word until you run out of characters.

As the comments say, it would have been nicer to let us know what you answered.

1 Comment

Let’s assume he didn’t have the answers in mind during his interview. Hence the question here.
0

You can use a for loop and pick substring using the ith value to the length of string to compare in loop.

string str = "axkfdspoipoujsdfpioneerfsdjkabcdxyzers";
string str2 = "pioneer";
bool isMatch = false;
if (str2.Length <= str.Length)
{
    for (int i = 0; i < str.Length-1; i++)
    {
        var check = str.Substring(i, str2.Length);
        if (str.Substring(i, str2.Length) == str2)
        {
            isMatch = true;
            break;
        }   
    }
}
return isMatch;

Comments

-2

try this:

    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;
    }

1 Comment

well a) this uses all sorts of in built functions b) its very inefficient

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.