lazygeniusLANZ
lazygeniusLANZ

Reputation: 21

Comparing a part of a string. C#

I want to compare and check if a string is a part of another string. For example: String1 = "ACGTAAG" String2 = "TAA"

I want to check if String1 contains String2. Im using this code but it does not work.

public bool ContainsSequence(string input, string toBeChecked)
    {
        for (int i = 0; i < input.Length; i++)
        {
            Char x = input[i];
            String y = Convert.ToString(x);

            for (int j = 0; j < toBeChecked.Length; j++)
            {
                Char a = toBeChecked[j];
                String b = Convert.ToString(a);
                if (b.Equals(y))
                {
                    j = toBeChecked.Length;
                    return true;
                }
            }

        }

        return false;
    }

input = string1 and tobechecked = string 2. Im new in c# so some terms may be confusing.

Upvotes: 0

Views: 252

Answers (4)

CoperNick
CoperNick

Reputation: 2533

For nucleotide sequences you probably want some sequence alignment algorithm which has some tolerance when sequences are not equal. For example Smith–Waterman algorithm.

Upvotes: 0

Laurentiu Ilici
Laurentiu Ilici

Reputation: 146

It looks to me like you're using this to compare DNA sequences :).

Maybe string.IndexOf(string value) or one of it's overloads is better for you because it can help you search for further occurences of the same string (stuff like "how many times does it contain the string"): http://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx

If indeed all you want is just to see if the string is contained, I'd also go for the versions provided by the others.

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

Use

If(mainString.Contains(searchedString)
{
   //do stuff
}

Upvotes: 0

SergioR
SergioR

Reputation: 48

try use String.Contains()

Check it out here:

http://msdn.microsoft.com/en-us/library/dy85x1sa%28v=vs.110%29.aspx

Good luck.

Upvotes: 1

Related Questions