- Home /
Get multiple variables through a string.
So I have ONE returned string saying something along the lines of: 'Hunger:100 Thirst:100 Strength:19' etc, etc. I also have variables, integer variables, called Hunger, Thirst, and Strength, respectively to the string. How would I go to assigning the Hunger variable to the 'Hunger:100' where it says 100 and the same for the other variables? I know this may be a little complicated, and I can't think of a way to do it yet. Thanks in advance, william9518
Do you have access to build the string in a different way? $$anonymous$$g put a pipe symbol between each variable type?
Ideally I would probably go with a standard data format like JSON, X$$anonymous$$L, YA$$anonymous$$L; though the simplicity of a dual-delimited string is ideal for really basic data.
Answer by DannyB · Sep 03, 2013 at 08:24 PM
Before you try to solve this problem you have created, I would try to eliminate it. It is not a healthy habit to work like this.
If you can return a dictionary instead of a string, do it.
If for some reason, you must return a string, then, the next logical step would be to try to receive it as dictionary. Meaning, instead of having a variable hunger
, have it stored in the dictionary, under the key "Hunger".
Now, if you can apply one of the above then it will be very easy with string.Split and a nice little loop:
For strings such as "Hunger:100:Health:200"
string[] tokens = receivedString.Split(':');
for( int i=0; i<tokens.Length-1; i+=2 ) {
myDictionary.Add( tokens[i], tokens[i+1] );
}
For strings such as "Hunger:100 Health:200"
string[] tokens = receivedString.Split(' ');
foreach( string token in tokens ) {
string keyValuePair[] = token.Split(':');
myDictionary.Add( keyValuePair[0], keyValuePair[1] );
}
Finally, if you still wish to maintain your int hunger
variable, then I would still use the above method, and after it is done, add lines such as:
hunger = myDictionary["Hunger"]
I totally agree. If you can fix the problem, go for it rather than patching up with strings.
$$anonymous$$UST return string because I am getting data off a mySQL database through PHP and I'm just in PHP using die("Hunger:100 Thirst:200"); and stuff like dat :( I will try the dictionary thx
Answer by numberkruncher · Sep 03, 2013 at 08:35 PM
The answer by @DannyB looks like its on the right track, though if I am not mistaken it is implemented incorrectly:
Edit: Lol, looks like @DannyB fixed their answer whilst I wrote my answer nm :)
public static Dictionary<string, string> ParseKeyValueString(string input) {
var data = new Dictionary<string, string>();
foreach (string arg in input.Split(' ')) {
var pair = arg.Split(':');
data[pair[0]] = pair[1];
}
return data;
}
Usage Example:
var data = ParseKeyValueString("Hunger:100 Thirst:100 Strength:19");
foreach (string key in data.Keys)
Debug.Log(string.Format("{0} = {1}", key, data[key]));