Strange behavior with Array Split from TextAsset

I can’t fathom what is happening here, if I setup an array like so:

string[] stringArray = {
        "string1",
        "string2",
        "string3",
   };

and then check to see if another string contains any strings from the array like so

string stringToCompare;
        foreach(string x in stringArray){
            if (stringToCompare.Contains(x))
            {
               Debug.Log("match");
            }
        }

It works perfectly, a match is triggered if stringToCompare contains any of the strings from the array.

However if I am getting the strings from a text file that is setup like so:
string1
string2
string3
and make an array from it like so:

public TextAsset textFile;
string fullText;

void Start(){
fullText = textFile.text;
stringArray = fullText.Split("\n"[0]);
}

and then run the comparison function, it only matches the last string in the array, in this example “string3” is the only string that will trigger a match if stringToCompare contains this string. It ignores all the other strings.

I’m not sure what I’m missing here seeing as the array is exactly the same in both cases, but getting a different result… I set it up with a for statement rather than a foreach, and no difference.

Any ideas?

It may be a line endings issue.

Instead of using “\n”[0] or ‘\n’ for your string.Split() argument, try using:

stringArray = fullText.Split( System.Environment.NewLine);

If it is a line ending problem, then each line except the last probably has a stray \r at the end of it, failing the match.

Before making the suggested above, you can verify this is the problem by iterating on the first string in your file and printing each character out, one at a time. I you have a stray ‘\r’ as the final character.

1 Like

Of course \r!

Thanks Kurt!