15,749,203 members
See more:
Hello all,

I am wondering if there is a way to find the piece of matching string in two strings?

Lets say I have
C#
```string str1 = "abcdyusdrahhMATCHhyweadh";
string str2 = "hbaiMATCHuncwenckdjrcaae";```

So how can I find the MATCH from these strings?

I used MATCH just to explain. The substring can be anything. so there is no particular string to look for. I need to find the longest matching substring.

Thanks.
Posted
Updated 25-Dec-11 22:46pm
v2

## Solution 1

It's called the Longest Common Substring, and there is a C# implementation here: Longest Common Substring[^]

RaisKazi 26-Dec-11 5:23am
wonder-FOOL 26-Dec-11 23:49pm

## Solution 4

Try
Algorithm Implementation/Strings/Longest common substring[^]
C#
```public int LongestCommonSubstring(string str1, string str2)
{
if (String.IsNullOrEmpty(str1) || String.IsNullOrEmpty(str2))
return 0;

int[,] num = new int[str1.Length, str2.Length];
int maxlen = 0;

for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
if (str1[i] != str2[j])
num[i, j] = 0;
else
{
if ((i == 0) || (j == 0))
num[i, j] = 1;
else
num[i, j] = 1 + num[i - 1, j - 1];

if (num[i, j] > maxlen)
{
maxlen = num[i, j];
}
}
}
}
return maxlen;```

v2
wonder-FOOL 26-Dec-11 23:52pm
although it is answered later than the other 2 solutions your solution is correct i will also accept it. thanks
RaviRanjanKr 27-Dec-11 6:35am
Thanks For Accept it. :)

## Solution 2

wonder-FOOL 26-Dec-11 23:50pm

## Solution 3

C#
```void CompareTwoSTring()
{
string[] Arrayvalue1 = new string[100];
string[] Arrayvalue2 = new string[100];
string values=null;
string firsValue = "1234567";
string secondValue = "12476";

for (int i = 0; i < firsValue.Length; i++)
{
Arrayvalue1[i] = firsValue[i].ToString();
for (int j = 0; j < secondValue.Length; j++)
{
Arrayvalue2[j] = secondValue[j].ToString();
if (Arrayvalue1[i].ToString() == Arrayvalue2[j].ToString())
{
values = values + Arrayvalue1[i];

}
}
}

MessageBox.Show(values);

}```