- Home /
Duplicate Question
How to split a string into array?
I try using the .Split function like this:
var text = "this is a test bla bla bla this this this";
var textSplit;
function Start () {
textSplit = text.Split(" "[0]);
Debug.Log(textSplit[3]);
}
If I do this Unity acts as I suspect it would by returning "test".
Debug.Log(textSplit[4]);
If I run this or anything higher I get the error message IndexOutOfRangeException: index
Debug.Log(textSplit.length);
Tells me 4
I can't find what the [0] is needed for. If I put anything else then 0 in there I get the error: IndexOutOfRangeException: Array index is out of range.
The following did return errors:
textSplit = text.split(" ");
textSplit = text.Split(" ",[0]);
textSplit = text.Split(" ");
Is there another function or am I doing something wrong here?
Thanks for your help.
Answer by fafase · Mar 25, 2014 at 08:18 AM
var str = "A string with many words";
var strArr:string[];
function Start(){
strArr= str.Split(" ");
}
I guess that should do it.
Answer by SirCrazyNugget · Mar 25, 2014 at 08:14 AM
Define textSplit as a string array:
#pragma strict
var text = "this is a test bla bla bla this this this";
var textSplit : String[];
function Start () {
textSplit = text.Split(" "[0]);
Debug.Log (text); //this is a test bla bla bla this this this
Debug.Log (textSplit); //System.String[]
for(var i : int = 0; i < textSplit.Length; i++){
Debug.Log(textSplit[i]); //each split
}
Debug.Log (textSplit[1]); //is
Debug.Log (textSplit[3]); //test
}
why the '[0]'? instead of the first character of a string, you should use a character instead by using single quotes. you can store characters in variables with 'char' like this:
char letter = 'a';
That's exactly the point, character literaly did not exist in UnityScript (which was Unity's javascript inspired dialect). It you needed a character literal you had to use a string and grab a single character from that string. Of course if the string only has one character you can only use the index 0. Like Fafase showed the Split method also has an overload that can split on strings rather than single chars which would work as well.
The original code should have worked just fine, I'm not sure why his array would only have 4 elements since his source text had more words in it. However maybe the "spaces" weren't normal spaces, who knows.
Follow this Question
Related Questions
convert string to list of lists 1 Answer
Split string from PlayePrefs 1 Answer
How to convert a string to int array in Unity C# 1 Answer
String split script 1 Answer
Array of Array 1 Answer