user3848181
user3848181

Reputation: 47

Remove first characters of values in comma separated string

I have the below comma separated string in application

string s= "01334644,1376673,1378437,01499972,1507527,01522373,01551596"; 

I want to remove the first character of each values in the string ..if it is zero

Finally i need a string like this

string s = "1334644,1376673,1378437,1499972,1507527,1522373,1551596"; // out put string  1

Upvotes: 0

Views: 3776

Answers (7)

mazharenko
mazharenko

Reputation: 635

What about regular expressions?

string s = "01334644,1376673,1378437,01499972,1507527,01522373,01551596";
string result = Regex.Replace(s, @"0*(\d+)", "$1");

0* means any quantity of zeros, \d+ means one or more digits, ( ) say to make a group, that we can call with $1.

Tested, I think, even works fine with strings like "00,000001972000,000". In this case several zeros became single.

Upvotes: 0

Perfect28
Perfect28

Reputation: 11317

Here is a way you can do it :

string s = "01334644,1376673,1378437,01499972,1507527,01522373,01551596";
String result = String.Join(",", s.Split(',')
                .Select(c => Convert.ToInt32(c).ToString()));

Upvotes: 1

Suji
Suji

Reputation: 1326

string[] str = null;
string s = "01334644,1376673,1378437,01499972,1507527,01522373,01551596";
str = s.Split(",");
s = "";
for (int i = 0; i <= str.Length - 1; i++) {
    s = s + Conversion.str(i).Substring(1) + " ,";
}
    // to avoid the last comma
Interaction.MsgBox(s.Trim(","));

Upvotes: 0

Neel
Neel

Reputation: 11731

 string s= "01334644,1376673,1378437,01499972,1507527,01522373,01551596"; 
 var str = string.Join(",", s.Split(',').Select(strCheck => strCheck.StartsWith("0") ? strCheck.Substring(1) : strCheck));

Upvotes: 0

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 303

Cast the value to int und back to String:

var values = s.Split(',').Cast<int>();
s = string.Join(",", values);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use String.Split to get all tokens and TrimStart('0') to remove leading zeros, String.Join to concatenate the final string again with commas:

string s= "01334644,1376673,1378437,01499972,1507527,01522373,01551596";
s = string.Join(",", s.Split(',').Select(str => str.TrimStart('0')));

... remove the first character ...

If you don't want to remove all leading zeros but only one at the maximum:

s = string.Join(",", s.Split(',')
    .Select(str => str.StartsWith("0") ? str.Substring(1) : str));

Upvotes: 3

ederbf
ederbf

Reputation: 1713

You can work directly in the source string to remove all 0 preceded by a comma:

string s2 = s.Replace(",0", ",").TrimStart('0')

Upvotes: 2

Related Questions