user9063755
user9063755

Reputation:

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

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.

Upvotes: 0

Views: 1190

Answers (6)

user8139876
user8139876

Reputation: 1

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;

Upvotes: 0

Krishna Sonune
Krishna Sonune

Reputation: 21

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

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391306

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

Upvotes: 1

pm100
pm100

Reputation: 50110

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

Upvotes: 3

realexweb
realexweb

Reputation: 33

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

Upvotes: -2

AndrewW
AndrewW

Reputation: 11

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.

Upvotes: 0

Related Questions