Comparing string

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

How can i compare 2 strings and extract the difference?

string1="abc zxy"
string2="abc 123 zxy 234"

extractedString ={"123", "234"}

thanks

Aaron
 
Aaron said:
How can i compare 2 strings and extract the difference?
string1="abc zxy"
string2="abc 123 zxy 234"
extractedString ={"123", "234"}

You probably have to write your own routine... What happens with "abc 123
def 456" and "abc ab c"? you probably have to define these behaviors
yourself for your own situation...
 
I thought this was a very common feature.

diffString = string1 - string2;//this doesn't work
 
Aaron said:
How can i compare 2 strings and extract the difference?

string1="abc zxy"
string2="abc 123 zxy 234"

extractedString ={"123", "234"}

thanks

Aaron

Never seen a language which has a built in function for that. What you do
is not even a real substraction since you let go spaces in between. But if
you want something like above and you are sure that every part of string1 is
in string 2 you can try using regex or the split function and then loop to
both arrays to find the differences :

static void Main(string[] args)
{
string string1 = "abc xyz";
string string2 = "abc 123 xyz 234";
string [] string1Array = string1.Split();
string [] string2Array = string2.Split();
int pos = 0; // pos in first array

for (int i = 0; i < string2Array.Length; i++)
if (pos < string1Array.Length &&
string2Array.Equals(string1Array[pos]))
pos++;
else
Console.WriteLine("{0}", string2Array);
}

Yves
 
I am pretty sure you will need to write your own method to do it. I
would write a method that takes each word in the shortest string and
attempts to find each word in the longer string. If the word can't be
found in the longer string then there is one difference.
 
Back
Top