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,

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][1] 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*, 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”]
    [1]: C# Split String Examples - Dot Net Perls

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 :slight_smile:

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]));