- Home /
How to split string into two integers?
I want to do UI InputField in which you'd enter minimum and maximum amounts, for example 3-7 and then trough script split them into two different integers.
It doesn't have to be fast by code, but I don't want it to be too messy either.
I've tried googling trough, but I've found totally irrelavant stuff such as string.split
Though, I've just got an idea to try split it to two strings without the "-" and then parse those two strings into integer. It's particularly late here so I'll go sleep and try this after I'm back to PC.
Answer by DonHaul · Aug 03, 2015 at 08:22 AM
Something like this should work
string str = //contents of the inputfieldstring;
string[] minmax= str.Split('-');
int min= int.Parse (minmax[0]);
int max= int.Parse (minmax[1]);
Oh wow! So many great and somewhat similar responses. I'll accept yours because you were first, but I'll +1 others too, thanks!
Answer by GiyomuGames · Aug 03, 2015 at 02:44 AM
You should split your string using regular expressions https://msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx
string input = "3-7";
string pattern = "-"; // Split on hyphens
string[] substrings = Regex.Split(input, pattern);
Then in your substrings object you should have "3" and "7" which you can easily put back into integers (Int32.Parse(substrings[0]) and Int32.Parse(substrings[1])). https://msdn.microsoft.com/en-us/library/bb397679.aspx
Answer by NeverHopeless · Aug 03, 2015 at 08:35 AM
Another simple possiblity is to use Split
with convertAll
. You don't have to extract and convert each element by yourself. Try like this:
string sample = "3-7";
int[] arr = System.Array.ConvertAll(sample.Split('-'), new System.Converter<string, int>(int.Parse));
Verify using:
foreach (var element in arr) {
Debug.Log(element);
}
Now you can use it like:
Debug.Log(arr[0]); // Prints 3
Debug.Log(arr[1]); // Prints 7
Your answer
Follow this Question
Related Questions
Using Strings To Call Function 1 Answer
Why can't I save an array? 1 Answer
Convert string to text in InputField 1 Answer
Sequential GameObject Activation 2 Answers
Get string from InputField 1 Answer