user3816352
user3816352

Reputation: 187

How to remove Whitespce from stringArray formed based on whitespace

I have a string which contains value like.

90  524           000   1234567890       2207 1926    00:34     02:40  S  

Now i have broken this string into string Array based on white-space.Now i want to create one more string array into such a way so that all the white-space gets removed and it contains only real value.

Also i want to get the position of the string array element from the original string array based on the selection from the new string array formed by removing white space.

Please help me.

Upvotes: 0

Views: 176

Answers (3)

Selman Genç
Selman Genç

Reputation: 101681

You can use StringSplitOptions.RemoveEmptyEntries via String.Split.

var values = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);

StringSplitOptions.RemoveEmptyEntries: The return value does not include array elements that contain an empty string

When the Split method encounters two consecutive white-space it will return an empty string.Using StringSplitOptions.RemoveEmptyEntries will remove the empty strings and give you only the values you want.

You can also achieve this using LINQ

var values = input.Split().Where(x => x != string.Empty).ToArray();

Edit: If I understand you correctly you want the positions of the values in your old array. If so you can do this by creating a dictionary where the keys are the actual values and the values are indexes:

var oldValues = input.Split(' ');
var values = input.Split().Where(x => x != string.Empty).ToArray();

var indexes = values.ToDictionary(x => x, x => Array.IndexOf(oldValues, x));

Then indexes["1234567890"] will give you the position of 1234567890 in the first array.

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460098

You can use StringSplitOptions.RemoveEmptyEntries:

string[] arr = str.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

Note that i've also added tab character as delimiter. There are other white-space characters like the line separator character, add as desired. Full list here.

Upvotes: 2

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

string s = "90  524           000   1234567890       2207 1926    00:34     02:40  S  ";
s.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x))

Upvotes: 1

Related Questions