Ye Myat Aung
Ye Myat Aung

Reputation: 1853

Remove empty space from number string?

I'm trying to remove any white space in the number from the textbox (txtAllNum) before converting them into an array. But I got the Input string was not in a correct format. error at the attempt to convert them to array.

Please advice.

(The list of numbers which will be inserted already have spaces at the beginning so I can't reject them with validation)

string allNumStr = txtAllNum.Text;
allNumStr = allNumStr.Replace(" ", "");

var intAry = allNumStr
   .Split(new string[] { Environment.NewLine }, 
          StringSplitOptions.RemoveEmptyEntries)
   .Select(s => Int64.Parse(s));

Here is the sample input data (They have a spaces at the beginning)

 95949323114
 9592099619
 9595173327
 95943054737
 95943090230
 95991046911
 9595028775
 95943173776
 95973494329
 95973082074
 95973000239

Upvotes: 1

Views: 884

Answers (2)

McAden
McAden

Reputation: 13970

Adding in a Where should do the trick. I have compiled this and tested this and it accounts for both leading and trailing whitespace, as well as blank entries.

Also, this assumes .Net 4 (string.IsNullOrWhiteSpace). You'll need to change the where statement if using anything less.

string allNumStr = txtAllNum.Text;
var intAry = allNumStr
    .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Select(s => Int64.Parse(s.Trim()));

Upvotes: 1

Uwe Keim
Uwe Keim

Reputation: 40756

Based on your example, would a simple TrimStart() call help?

string allNumStr = txtAllNum.Text;
allNumStr = allNumStr.Replace(" ", "");

var intAry = allNumStr
   .Split(new string[] { Environment.NewLine }, 
          StringSplitOptions.RemoveEmptyEntries)
   .Select(s => Int64.Parse(s.TrimStart()));

Upvotes: 1

Related Questions