Compare two strings: Get all positions of differences

  • Thread starter Thread starter Sasidhar Parvatham
  • Start date Start date
S

Sasidhar Parvatham

Hi All,

How do I compare two strings and get all the positions where there is a
difference between them?

Thanks,
Sasidhar
 
Sasidhar,

You are going to have to do this manually. Basically, you would cycle
through each character in one string, and compare it to the corresponding
character in the other. If the string or the character doesn't exist, then
there is a difference (I assume the strings will be of different lengths).

Hope this helps.
 
Hi Sasidhar

This will do it (hope I'm not doing your homework :) and if so, make sure
you understand the code fully :P)

ArrayList list = new ArrayList();
string s = "Hello World";
string t = "Getto Word";

for(int i = 0; i < s.Length; i++)
{
if(i >= t.Length)
list.Add(i);
else if(s != t)
list.Add(i);
}

// if you also want virtual positions if s is the shortest string
if(t.Length > s.Length)
{
for(int i = s.Length; i <= t.Length; i++)
list.Add(i);
}

// optional, the list will contain all positions
int[] indices = (int[])list.ToArray(typeof(int));
 
Thanks Nocholas and Morten.

I am aware of this method. I was looking for any other efficient way to do
this. Your responses confirmed that there is no better way to do this than
the one you guys suggested.

I was looking whether there is a way we can use FC (DOS file compare) to do
this or some other alternative.

Anyhow thank you once again for your responses.
Sasidhar
 
" A Generic, Reusable Diff Algorithm in C# "

http://codeproject.com/csharp/DiffEngine.asp

HTH,
Alexander

Sasidhar Parvatham said:
Thanks Nocholas and Morten.

I am aware of this method. I was looking for any other efficient way to do
this. Your responses confirmed that there is no better way to do this than
the one you guys suggested.

I was looking whether there is a way we can use FC (DOS file compare) to
do
this or some other alternative.

Anyhow thank you once again for your responses.
Sasidhar


Morten Wennevik said:
Hi Sasidhar

This will do it (hope I'm not doing your homework :) and if so, make sure
you understand the code fully :P)

ArrayList list = new ArrayList();
string s = "Hello World";
string t = "Getto Word";

for(int i = 0; i < s.Length; i)
{
if(i >= t.Length)
list.Add(i);
else if(s != t)
list.Add(i);
}

// if you also want virtual positions if s is the shortest string
if(t.Length > s.Length)
{
for(int i = s.Length; i <= t.Length; i)
list.Add(i);
}

// optional, the list will contain all positions
int[] indices = (int[])list.ToArray(typeof(int));
 
Back
Top