- Home /
Reading integer value from specified character(s) on text line?
Hi, I'm trying to figure out how to get the 1 out of "player_skilldata_Standard Weapons=1;" (Value example)
How do I go about doing this? Perhaps I could use "=" as a start and ";" as an end, but how? I'm close to creating a saving/loading system with serialized values, and I just need to figure out how to load the values back into the game.
Answer by HarshadK · Mar 18, 2015 at 09:32 AM
You can do it using the method below. It is taken from this question on Stack Overflow: How do I extract text that lies between parentheses
public string GetNestedString(string str, char start, char end)
{
int s = -1;
int i = -1;
while (++i < str.Length)
if (str[i] == start)
{
s = i;
break;
}
int e = -1;
while(++i < str.Length)
if (str[i] == end)
{
e = i;
break;
}
if (e > s)
return str.Substring(s + 1, e - s - 1);
return null;
}
When you call the above method just pass argument parameters as below:
string value = GetNestedString("player_skilldata_Standard Weapons=1;", '=', ';');
This will return a string representation of "1", which is the desired value which you can then convert to an integer using:
int weaponValue = Int32.Parse(value);
You can also use Int32.TryParse instead of Int32.Parse to avoid being thrown an exception.
This is a nice answer, I had to tweak it due to a problem where I am unable to call certain commands inside of my static load method.
I'd love to share the results here, but there is a character limit.
Remember to establish the SaveSystemValues with your own serialized list of skills, inventory items, (etc) before saving or loading, otherwise you won't get any result.
Answer by raulrsd · Mar 18, 2015 at 09:43 AM
You could try this instruction:
string s = "player_skilldata_Standard Weapons=1;";
s = s.Substring(s.IndexOf('=')+1,s.IndexOf(';')-s.IndexOf('=')-1);
And just in case you want convert the string number to float:
float f = float.Parse(s);