- Home /
Extracting list of floats from string C#
Hey guys!!
I have just run into something I haven't managed to get my head around. I have a string which contains a varying amount of floats which are varying lengths. I need to extract each float and place them in a List.
Here's an example:
This is the string:
[0.00442398712038994, 0.640771448612213, 0.830118358135223, 1.1674565076828, 1.52580320835114, 1.57927715778351]
I want it to be split up into as many number of floats as there are numbers here.
I only need help with splitting. I know how to put it in a list. The only reason I'm having trouble with this is the fact that there isn't really a consistent separation that I can see.
Usually I would use:
string[] splitter = {"\", \""};
string[] namesArray = input.Substring(2, input.Length-4).Split(splitter, System.StringSplitOptions.None);
foreach (var name in namesArray) {
string nameInput = nameStringJSON;
string name = nameInput.Substring(55, nameInput.Length-57);
print("name");
}
Maybe there is some way of extracting floats and placing them in a list?
They're all separated by a comma? Seems consistent to me.
I think maybe I'm just being a noob and missing something here. With the other ones they were separated from each other with "'s at the beginning and end which made it easy to split them, but here I have just commas at the end and also a [ at the beginning of the entire string and a ] at the end
But after writing this I realised I could have simply cut the [ ] off and split using the spaces as the beginning and ,'s as the ends
Ah sorry for that guys
$$anonymous$$y answer below is pretty short for doing this, you could just make it:
var myArray = inputTextString.Replace("[","").Replace("]","").Split(',').Select(Convert.ToSingle).ToArray();
And don't worry about it - I've asked plenty of odd questions myself :)
Answer by whydoidoit · May 27, 2012 at 12:45 AM
Try this:
using System.Linq;
using System.Collections.Generic;
var myList = inputTextString.Split(',').Select(Convert.ToSingle).ToList();
or
var myArray = inputTextString.Split(',').Select(Convert.ToSingle).ToArray();
Your answer
![](https://koobas.hobune.stream/wayback/20220613072004im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Input string is not in correct format 1 Answer
Store individual positions of GameObjects in a string 3 Answers
How to convert a float to a string and then have it appear in a gui rect 3 Answers
Make String Update for Value (GUI) 1 Answer
Unity Convert more int to one float or String and back? 1 Answer