User_4373
User_4373

Reputation: 297

C# split the string by white-spaces and remove the comma

I have the string as: बिहिबार, साउन ९, २०७६

I wanted to separate the each character into a array, removing , and spaces

Output as:

बिहिबार
साउन
९
२०७६

I have tried to split the string first and remove the comma using the code:

input.Split(@"\s+").Select(x => x.Replace(",", ""));

However i have got the output as list of string as

enter image description here

Upvotes: 0

Views: 3829

Answers (3)

eye_am_groot
eye_am_groot

Reputation: 682

I wanted to separate the each character into a array, removing , and spaces

Assume that this is actually what you want, and each of the connected symbols is it's own char, something like this should work:

string myst = "hi , this, is a, test";
char[] myar = myst.Replace(",", string.Empty).Replace(" ", string.Empty).ToCharArray();

If you want to split by spaces and commas (and not split each character to a char array):

string[] myar = myst.Split(new char [] {',' , ' '}).Where(x => !string.IsNullOrEmpty(x)).ToArray();

Upvotes: 2

NappingRabbit
NappingRabbit

Reputation: 1918

you can remove the commas and replace the spaces with newlines using the following:

string str = dateSpan.Replace(",","").Replace(" ", Environment.NewLine);

this does not create the array you were looking at, but does give the output you were looking for.

something closer to what you were doing is maybe:

var aStrs = 
    dateSpan.Split(" ,".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries).ToArray();

I know you said you want a char array, but it seems you want an array of strings. If you want them as character arrays, just loop through them and do .ToCharArray()

Upvotes: 3

TVOHM
TVOHM

Reputation: 2742

Firstly, let's figure out the problem, then we can figure out how to fix it.

Let's break your expression out to make it easier to understand what's going on, firstly:

string[] split = input.Split(@"\s+"); // [0] = "बिहिबार, साउन ९, २०७६"

So, something is amiss before we even get to replacing the commas! Split is not correct, you are not splitting on a space like you think you are.

Let's just swap it out with a space (were you trying to use Regex there?):

var split = input.Split(" ")
    .Select(x => x.Replace(",", ""));

Et Voila! You have debugged your way to the result you expect.

Edit: If we're discussing regex, you could do:

string[] split = Regex.Split(input, ",? +");

I believe you understand the how Regex and String split methods work, but by using this regex you can just straight up split your input string on 'an optional comma (,?) and then one or more spaces ( +)'.

Upvotes: 2

Related Questions