简体   繁体   English

x量相同后拆分字符串

[英]Split string after x amount of same number

I need to split a string in C# as follows: 我需要在C#中拆分字符串,如下所示:

The string is something like this: 0000120400567 字符串是这样的: 0000120400567

There are always 0 s at the beginning. 一开始总是0秒。 In the example above there are six zeros followed by 120400567 . 在上面的示例中,有六个零,后跟120400567 I want to split the string that I get the last part 120400567 . 我想拆分我得到最后一部分120400567的字符串。

The amount of zeros at the beginning might change (the last part number will increase by one number) that means we can have 001245878945 and what I want is 1245878945 . 开头的零数量可能会改变(最后一个零件号将增加一个数字),这意味着我们可以拥有001245878945 ,我想要的是1245878945

How can I split this string leaving off the first 0 or the first x amount of zeros and get the end number only? 如何分割此字符串,从而忽略前0或前x个零,并仅获得结束编号? It might be so that the number don't have any zero at the beginning and the number starts directly from the first number ... but it might be that the number contains 8 zeros and than 2 or more number of digits. 可能是这个数字在开头没有任何零,而数字直接从第一个数字开始......但可能是数字包含8个零而不是2个或更多个数字。

string withoutLeadingZeroes = withLeadingZeroes.TrimStart('0');

(or (要么

string withoutLeadingZeroes = Regex.Replace(withLeadingZeroes, "^0*", "");

or 要么

string withoutLeadingZeroes = new String(
    withLeadingZeroes.SkipWhile(c => c == '0').ToArray());

or ...) 要么 ...)

TrimStart is your friend. TrimStart是你的朋友。 However, you need to be careful that you don't end up with an empty string when your original consists of 0s only. 但是,当原始字符仅包含0时,您需要注意不要以空字符串结尾。

string s = "0000120400567";
s = s.TrimStart('0');
if (s == "")
    s = "0";

You could use int.Parse to convert the String into an Integer. 您可以使用int.Parse将String转换为Integer。 This would drop leading zeros, but is of course limited to strings within the range of int (or long, if you use it). 这会丢弃前导零,但当然限于int范围内的字符串(如果你使用它,则为long)。

Why don't you convert it into int32 or long or whatever you want and then convert it into a string ? 为什么不将它转换为int32或long或任何你想要的,然后将其转换为字符串?

int i = int.Parse("0000120400567");
        string s = i.ToString();

If you have a range of numbers in the string you can use (?:\\b(?:0+|(?=[1-9]))) to split that string 如果您在字符串中有一系列数字,您可以使用(?:\\b(?:0+|(?=[1-9])))来分割该字符串

So splitting 0534 000500 35435 040 with the above regex would end up with 所以将0534 000500 35435 040与上述regex分开将最终得到

534 
500
35435 
40

If it's going to contain only a single number Regex is not required then and especially splitting it 如果它只包含一个数字,则不需要Regex ,特别是splitting

But if you still want to split that string,you can do it with (?:^0+|^) 但是,如果您仍想split该字符串,可以使用(?:^0+|^)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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