comparing 2 strings (C#)

Started by
15 comments, last by rob64464 20 years, 1 month ago
Hello, I have to strings: string test1 = "bceasue" //notice bad spelling string test2 = "because" //notice correct spelling. ok, here is the problem. I am trying to detect is test1 has exactly the same letters as test2. How do I do it? Something to do with character arrays? Its just I am making a word game and I need to detect if a jumbled up letter actully makes a word. Thanks, Rob
Advertisement
My first instinct is to convert both strings to char arrays with String.ToCharArray(). Then sort both char arrays with Array.Sort() and then compare the char arrays for equality.
thank you! Ill see if that works! I managed to get both strings to char arrays! Never new about the sort command though.

Thank You,
Rob
If you have to use char arrays for one reason or another, strings ARE char arrays. Just access each character via indexer as you usually would;

test1[0]
test1[1]
.. etc

EDIT:

You can also do a foreach loop;

foreach (char c in test1) {
// ..
}

[edited by - wyrd on March 22, 2004 5:51:01 PM]
That will not work because the word 'because' can change to any word in the dictionairy. Is there any command to split a string into characters and compare the 2 to see if they contain exactly the same characters?

[edited by - rob64464 on March 22, 2004 5:58:18 PM]
thats what sort is for. Wont that sort it numerically?
So Because becomes abceesu
& Beausce becomes abceesu then you loop at check SR1 == SR2 </i>
so that code will work, yeah?

Thanks,
Rob
Array.Sort(test1.ToCharArray());
Array.Sort(test2.ToCharArray());
MessageBox.Show(test1.ToString());
MessageBox.Show(test2.ToString());

that does not change the string. It still gives out bceause and because.
You''re converting the strings to temporary arrays, sorting the temporary arrays and throwing the temporary arrays away. You need to keep the arrays that you''ve sorted around. ex:
static bool comp(string s1, string s2) {	char [] a1 = s1.ToCharArray();	char [] a2 = s2.ToCharArray();	Array.Sort(a1);	Array.Sort(a2);	return a1.ToString() == a2.ToString();} 
Ummm, did you ever try:

if (string1 == string2) {
// same
} else {
// not same
}

This topic is closed to new replies.

Advertisement