Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Monday, May 27, 2013

How do I split a string containing one or more spaces in C#?


Problem:I want to split a string if there is a space between words.

For example:
"Blood Doner Jack Stv 240 o+"
When I split it using a single space it returns an array object with 6 items, but if I try it with the same set of text and there are 2 spaces in place of one it increase the array to 7:
"Blood  Doner Jack Stv 240 o+"
So I want to know how to remove split it with a double space as well as a single.
I know I can use Replace() with 2 spaces to 1 space but what if I have 3 or 4 spaces?

Solution :

In this you can use Reg Expression:
Regex r = new Regex(" +");

Suppose 'AI   23MNNB     57HJHGH' is a string .now if you want to split it using substring or split method of string then you will not split it because it contains multiple spaces.
But In this if u use Reg Expression then it will split your words ignoring spaces.
Then Output will: 
AI
23MNNB
57HJHGH

Now u can use as your needs.
N.B: It will work in single space as well as multiple spaces.


Enjoy......

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here