- Home /
Extracting Numbers from String Place JS
I'm trying to create a multidimensional array using only one string. Let's say the printed output of turn[45] is:
Turns45 Lives39 Posx76.899 Posy3.445
How would I go about extracting the string into four separate ints like this:
Turns = 45
Lives = 39
Posx = 76.899
Posy = 3.445
Thanks!
Answer by Epicwolf · Oct 21, 2014 at 05:52 PM
You could easily use string.Split for this, however, you would need to have some sort of separator between the variable names and values, like this:
bigstring = "Turns=45 Lives=39 Posx=76.899 Posy=3.445";
Then you could split the string by spaces by doing this:
// The [0] is needed in C#, but I dunno about js.
stringarray = bigstring.Split(" "[0]);
Which would return a string array like this:
[ "Turns=45" , "Lives=39" , "Posx=76.899" , "Posy=3.445" ]
Finally, you could split the strings in stringarray by "=", and store the values.
// these lines of code take each element from the array, split the by the "=", and set the variable to
// the second item in the array that returns.
//
// For example, for Turns, the first item ( "Turns=45" ) is split,
// which returns this: [ "Turns" , "45" ]
// Then the second item, the "45", is converted to an int: 45
// and is finally stored in Turns.
//
// This proccess is repeated for each variable, except Posx and Posy are floats.
//
Turns = int.Parse(stringarray[0].Split("="[0])[1]);
Lives = int.Parse(stringarray[1].Split("="[0])[1]);
Posx = float.Parse(stringarray[2].Split("="[0])[1]);
Posy = float.Parse(stringarray[3].Split("="[0])[1]);
Your answer
Follow this Question
Related Questions
How to convert a string to int array in Unity C# 1 Answer
bool[string] = true; array possible? 2 Answers
Array - Convert Object into Int 5 Answers
Converting a string to an int 2 Answers
Convert Array to String 3 Answers