简体   繁体   中英

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

如果您进一步处理数组以连接连续的char.isdigit()字符,或者无法使用快速的1命令解决方案imo,string.ToCharArray()可以工作,或者可以通过配置使用String.split方法提取100、12和41个块您正确地分隔,并用string.ToCharArray分割其余部分。

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM