justuser
justuser

Reputation: 355

C# How can i split a string correctly?

((100&12)%41)&(43&144) this is my string and i want to split this string like this:

(
(
100
&
12
41
)....

I try using string.ToCharArray() method but big integer numbers brings a problem like 100:

1
0
0

thanks for help

Upvotes: 0

Views: 160

Answers (5)

BLUEPIXY
BLUEPIXY

Reputation: 40145

using System;
using System.Text.RegularExpressions;
class Sample {
    public static void Main(){
        var str = "((100&12)%41)&(43&144)";
        var pat = "([()&%])";
        var tokens = Regex.Split(str,pat);
        foreach(var token in tokens){
            if( !string.IsNullOrEmpty(token))
                Console.WriteLine("{0}", token);
        }
    }
}

Upvotes: 0

Sergey Gavruk
Sergey Gavruk

Reputation: 3558

It returns the list of lines:

static List<string> SplitLine(string str)
        {
            var lines = new List<string>();

            for (int i = 0; i < str.Length; i++)
            {
                if (!char.IsDigit(str[i]))
                {
                    lines.Add(str[i].ToString());
                    continue;
                }
                string digit = "";
                while (char.IsDigit(str[i]))
                {
                    digit += str[i++];
                }
                i--;
                lines.Add(digit);
            }

            return lines;
        }

Output:

(
(
100
&
12
)
%
41
)
&
(
43
&
144
)

Upvotes: 1

Saeed Amiri
Saeed Amiri

Reputation: 22555

You can write your own tokenizer, but for help is usefull to have sth like this(code is not tested):

var lst = new List<string>();
for (int i=0;i<str.Length;i++)
{

 if (char.IsDigit(str[i])
 {
    var tmp = new string(new []{str[i]});
    i++;
    while(i<str.Length && char.IsDigit(str[i]))
       { tmp+= str[i]; i++}
    i--;
    lst.Add(tmp);
 }
 else
  lst .Add(new string(new []{str[i]}));
}

Upvotes: 1

JustMeGaaRa
JustMeGaaRa

Reputation: 520

try iterating through you string and watch if next char is a digit. If false then split, else skip

Upvotes: 1

TigOldBitties
TigOldBitties

Reputation: 1337

No fast 1 command solution here imo, string.ToCharArray() can work if you further process your array to concatenate consecutive char.isdigit() chars, or you can use String.split method to extract the 100, 12 and 41 blocks by configuring you separators properly, and string.ToCharArray to split the rest.

Upvotes: 1

Related Questions