Hello all,
I’m working on a script now that will read some code that a user has typed on a keyboard in-game and parse it so that I can send those codes to start different commands. The codes will be a single uppercase letter followed be a series of numbers. Many different codes can be entered on a single line. The code will look something like this: “G10M8X5Y5”, and I’d like to get something like this out of it: “G10”,“M8”,“X5”,“Y5”.
What parsing technique will I need to use in order to accomplish this?
Thanks!
Could be done with Regex and matches, here is a super simple version that should be easy to follow.
string b = "G393Z47E18724F111";
StringBuilder sb = new StringBuilder();
List<string> output = new List<string>();
foreach( char c in b )
{
if( char.IsNumber(c) )
{
// if it's a number, lets add it to the current code.
sb.Append(c);
continue;
}
if( char.IsLetter(c) && sb.Length == 0 )
{
sb.Append(c);
continue;
}
if( char.IsLetter(c) && sb.Length > 0 )
{
// we assume we have hit a new code since the builder has more then 0 characters in it and the next char coming up is a letter.
// Lets add our previous code to the output List of string, then clear the stringbuild for the next one and append for the next code.
output.Add(sb.ToString());
sb.Clear();
sb.Append(c);
continue;
}
}
// Grab the last one that wasn't captured in the foreach loop:
output.Add(sb.ToString());
One will need to use System.Text for StringBuilder and System.Collections.Generic for the use of List. Plug this in where ever you want.
output is a List of string where each entry/element is a parsed value as you asked about.
You can use Split.
ex:
string allCodes = "G10,M8,X5,Y5";
// this splits the string using comma as a parameter.
// every index on the array will now have a code in it.
// note that this method requires you to use a single ' instead of "
string[] codes = allCodes.Split(',');
// prints on the screen all the codes
foreach(string current in codes)
{
Debug.Log(current);
}