C# string manipulation Regex or substring?


C# string manipulation Regex or substring?

I have a
string CCstring = “CC01=50 CC02=300 CC03=500 CC04=40”;

I want to store the individual values in seperate strings like:
for(int i = 0; i<=4; i++) { string suffix = i.ToString().PadLeft(2, '0'); string CCindividual = CCindividual + i; CCindividual = //THIS IS WHERE I WOULD LIKE TO GET MY INDIVIDUAL VALUES i.e 50,300,500,40; Console.WriteLn("CC" + i + " =" + CCIndividual);//Testing } Which string manipulation should I use Regex or Substring. How would the code snippet look like?


Solution 1:

One line:

string[] CCindividual = Regex.Split(CCstring, "CC[0-9]+=").Where(x => x != "").
    Select(x => x.Trim()).ToArray<String>();

Not sure this is the more efficient way though.

Solution 2:

Can’t you use split to first split on spaces and next on ‘=’? It’s easier than regex or substring imho.

Solution 3:

Neither. You can use string.Split to get an array:

string CCstring = "CC01=50 CC02=300 CC03=500 CC04=40";
string[] strings = CCstring.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

After that, you are able to do the same for the = using string.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);.

Solution 4:

Unless you need this code to run very very efficiently. You should be worried about what is readable for you and your team (sometimes thats substring, split etc and sometimes thats regex). Only you can really decide.

Solution 5:

just use String.Split

        string CCstring = "CC01=50 CC02=300 CC03=500 CC04=40";
        var result = CCstring.Split(' ')
            .Select(s => s.Split('='))
            .ToDictionary(kv => kv[0], kv => Convert.ToInt64(kv[1]));

Solution 6:

Looking at your CCstring it will be definitely faster to walk through the string characters just once. Sure it doesn’t worth that until you have tons of such strings.

So, yep, it’s easier to use just string.Split once for spaces, and once for each fragmet to split by ‘=’.