Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string after x amount of same number

I need to split a string in C# as follows:

The string is something like this: 0000120400567

There are always 0s at the beginning. In the example above there are six zeros followed by 120400567. I want to split the string that I get the last part 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.

How can I split this string leaving off the first 0 or the first x amount of zeros and get the end number only? 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.

like image 825
user1894670 Avatar asked Dec 11 '12 12:12

user1894670


2 Answers

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

(or

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

or

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

or ...)

like image 107
Rawling Avatar answered Oct 13 '22 14:10

Rawling


TrimStart is your friend. However, you need to be careful that you don't end up with an empty string when your original consists of 0s only.

string s = "0000120400567";
s = s.TrimStart('0');
if (s == "")
    s = "0";
like image 27
Douglas Avatar answered Oct 13 '22 13:10

Douglas