- Home /
How to parse a string between certain characters?
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!
Answer by Landern · Jun 25, 2015 at 06:00 PM
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.
This is exactly what I was looking for. Thank you so much!
Answer by brunopava · Jun 25, 2015 at 06:02 PM
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);
}
That would be too simple, notice that the original string does not contain any comas. Regex is a simple but ugly solution. Iteration through the string to find match is a more complex but more readable solution.
Your answer

Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
C# Variable 4 Answers
Can i give GetComponent a variabel instead of a scriptname? 1 Answer
Problem recognizing declaration of array of strings 1 Answer