C# compare values

Ok I know I can compare 2 strings or 2 lists pretty easily.

public string test1 = "book,case,that,other";
public string test2 = "book,case,notsame";
 
void Start() {
    if (test1 == test2) {
            Debug.Log("The Same");
    }
    else {
            Debug.Log("Different");
   }
}

In that example, Test1 and Test2 are different so Unity would return a value of Different.

Ok now here is my question. Lets say my variable changed and changed in length.
One moment it could be:
Test1 = “book,book,book,book,book,shubbery,”

The next moment it could be:
Test1 = “red,red,red,”

In that case, I wouldn’t be able to set up another string to test it against since it changes so much. The ultimate goal would be to take the values within Test1:

“book,book,book,book,book,shubbery”

And test them to see if they are all identical. So:
“book,book,book,book,” would be returned as all identical while
“book,book,pail,pail” would be returned as not identical.

So you have a string separated by the ‘,’ symbol, and you want to check if every element in the string is equal.

Pretty simple - split the string into an array, and check if every element is the same:

bool AllWordsEqual(string s) {
    string[] allStrings = s.Split(',');
    bool allEqual = true;
    for (int i = 1; i < allStrings.Length; i++) {
        if (allStrings[i] != allStrings[0])
            allEqual = false;
    }
    return allEqual;
}

Here, AllWordsEqual(“book,book,book”) will return true, while AllWordsEqual(“book,notbook,book”) will return false.

That should do it, but I do run into something here I really don’t understand fully. Whenever a method is written and returns a value, I’m not sure how to retrieve that value. I’m sure it works, but how do I access what it creates?

You just use what the methods returns as a value you give directly:

public string test1 = "book,book,book,book";
public string test2 = "book,notbook,book";

void Start() {

    //You can assign the value to a bool:
    bool test1AllEqual = AllWordsEqual(test1);
    if (test1AllEqual) {
        Debug.Log("All in 1 equal");
    }
    else {
        Debug.Log("All in 1 not equal!");
    }

    //Or just use it directly:
    if (AllWordsEqual(test2)) {
        Debug.Log("All in 2 equal");
    }
    else {
        Debug.Log("All in 2 not equal!");
    }
}

bool AllWordsEqual(string s) {
    string[] allStrings = s.Split(',');
    bool allEqual = true;
    for (int i = 1; i < allStrings.Length; i++) {
        if (allStrings[i] != allStrings[0])
            allEqual = false;
    }
    return allEqual;
}

Ah! Ok that makes sense!