sam
sam

Reputation: 31

How to remove leading 0 from a string with space in between in C#

I know how to remove the leading 0 if it does not have any space in between

var strVal = "000001234";
strVal.TrimStart('0');

will give result "1234". But i am not sure what to do with

var strVal ="0000 00001234";

I tried:

strVal.Trim().TrimStart('0');

but it returned "00001234". Can anyone please help.

Upvotes: 1

Views: 269

Answers (2)

Rufus L
Rufus L

Reputation: 37020

You can specify more than one character to remove from the start of the string when you call TrimStart, so you can simply include the space character:

"00 00123".TrimStart(' ', '0');

Upvotes: 5

Sweeper
Sweeper

Reputation: 270980

Trim wouldn't work because it:

Removes all leading and trailing white-space characters from the current String object.

It does not remove anything "inside" the string.

As an alternative to Rufus L's solution, here's a solution with regex:

using System.Text.RegularExpressions;

// ...

Console.WriteLine(Regex.Replace(strVal, "^[0\\s]+", ""));

Explanation:

  • ^: start of string
  • []: match any one thing inside the brackets
  • \\s: match any whitespace
  • + repeat this 1 or more times

Upvotes: 2

Related Questions