开发者

C# How can i split a string correctly?

开发者 https://www.devze.com 2023-04-13 09:58 出处:网络
((100&12)%41)&(43&144) this is my string and i want to split this string like this: ( ( 100 &

((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


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


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.


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


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
)


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);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消