C# Compare Strings?

Hello guys,
I am having an issue with comparing strings in C#. I used the simple:

if(str1 == str2){
    doSomething();
}

But it’s saying it can’t compare types ‘string’ and ‘string[ ]’ with ‘==’. I looked in the forums and it appears that at one point you were able to, but now I can’t? I tried some casts ( ‘int’ to many periods, ‘string[ ]’ couldn’t convert ).

Please let me know what your ideas are.

Thanks,

  • WolfShield

Compare them one at a time.

str1 and str2 are not both strings, one is an array of strings(hence string[ ]).
Either compare each element in the string one at a time or figure out why you are mistaking a group of strings with a single string.

So,
There is no function to just compare strings in Unity’s C#?

Also, when I tried:

if(String.Compare(str1, str2) == 0){
    someFunction();
}

It only said that ‘String’ was not in current context. Does that mean it’s an actual function and I just need to include ‘String’ in it somewhere? Or is that completely wrong?

Thanks,

  • WolfShield

What are you actually trying to do? Do you have an array of strings, and you’re trying to see if the string is in the array? If so, use Array.Contains.

–Eric

It’s actually some Networking stuff.
I’m comparing the comment section of the MasterServer, to the ip address of an element in MasterServer.

So the comment is of type ‘string’ and the ip address is of type ‘string[ ]’ because of the ‘.’ of course.

  • WolfShield

They are not of the same type, so I think it is obvious you have to change one or the other before comparing.

Type string and type string array are two different types, but that is resolved easily enough, something like this should work. keep in mind that you need to include the system namespace for access to String

        string[] strings = new string[10];
        string otherString = "whatever";

        foreach (string part in strings)
	{
            if (String.Equals(part, otherString))
            {
                //do something when its true
            }
            else
            {
                //do something when its not true;
            }
	}
1 Like

When you did String.Compare(), it developed an error b/c the class String doesn’t exist. It is called string (lowercase ‘S’).

No, you need to include system…

at the top of your file type using System

1 Like

Siegion,
Your solution worked flawlessly. Thank you very much!

And to everyone who replied, thank you for spending your time sharing your knowledge with me.

Sincerely,

  • WolfShield
1 Like

No problem =)

For the geeks among us, here’s a blog which benchmarks numerous ways to compare strings in C#:. The fastest way, according to the blog, is:
if (string.CompareOrdinal(stringsWeWantToSeeIfMatches[×], stringsWeAreComparingAgainst[×]) == 0)

_

3 Likes

You could also use linq. Although many of these responses are great, Linq will do this exact thing for us,. and its a nice clean one liner. All you need to do is include System.Linq.

In the background, it iwll still do its loop, but is optimised and clean.

using UnityEngine;
using System.Collections;
using System.Linq;

public class NewBehaviourScript : MonoBehaviour {
public void someFunc(){
string[ ] testArray = {“test1”, “test2”};

string testString = “test1”;
string noMatchString = “test5”;

bool testStringExists = testArray.Contains(testString);
bool noMatchStringExists = testArray.Contains(noMatchString);
}
}

1 Like

what if you were trying to compare a string to an enum return?

Cool Go for the first code only…That Worked

whats wrong with myString.Equals(myOtherString); is it slow?

Who said that anything is wrong with String.Equals?

There is nothing wrong with String.Equals.
There is a problem with myString.Equals since myString cannot be null.

its just no one mentioned it, thats the one that comes to mind instantly maybe because im a java coder by nature… But my question I guess is what is the fastest way to compare strings? and maye if anyone knows why is compareTag() quicker than comparing manually, it must do something special.

String equality becomes complicated because there’s a bunch of different ways to compare strings. See String.Equals and the StringComparison enum. None of that is slower than what’s reasonable for what you’re asking for, but if you’re doing a culture-sensitive comparison when what you really mean is “do these two strings have the same bytes”, you’re being slower than you need to.

String.Equals defaults the culture to CurrentCulture, which means that the behaviour depens on what computer it runs on, and is slower than the Ordinal (byte-by-byte) comparison.

Note that unlike Java, C# can override ==, so in C# == for strings checks content (byte) equality, not reference equality like in Java. So in C#, str1 == str2 is the same as str1.Equals(str2, StringComparison.Ordinal).

So in the vast, vast, vast majority of cases, str1 == str2 is what you’re looking for. In Java, str1 == str2 is almost always a bug.

CompareTag knows that there’s a limited number of tags, and that there’s no reason to care about any of that stuff, so it just compares the tag’s hash codes.

5 Likes