Click here to Skip to main content
15,881,680 members
Articles / Programming Languages / C#
Tip/Trick

Removing white space from a String

Rate me:
Please Sign up or sign in to vote.
2.71/5 (7 votes)
26 Jun 2010CPOL 36.8K   3   8
Simple Tip on how to remove / replace the white space in a string value
Have you ever faced the problem where you have a String that contains white space and would like to remove or replace it, e.g (00054 675 286).

Using the Replace() method, you can easily replace this space with any character you like, or if you need to totally remove it.

The first example shows the removal of the white space completely.

string mobileNumber = "00054 675 286"
mobileNumber = mobileNumber.Replace(" ",")


Output = 00054675286

The second example replaces the spaces with any charecter, for this example, we will be using the (/) character.

string mobileNumber = "00054 675 286"
mobileNumber = mobileNumber.Replace(" ","/")


Output = 00054/675/286

By using the Replace() method, you can replace any character you would like in a string with any other character.

Hope this simple but effective tip helps in the future.

- Nick Austin

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) DecodedSolutions.co.uk
United Kingdom United Kingdom
We are software developers and we specialise in all software development.

Visit Decoded Solutions NOW for all your development needs.

Comments and Discussions

 
GeneralReason for my vote of 2 trivial. wrong article name (space v... Pin
johannesnestler7-Jul-10 3:07
johannesnestler7-Jul-10 3:07 
GeneralReason for my vote of 1 default functions and bad performanc... Pin
BugByter3-Jul-10 4:26
BugByter3-Jul-10 4:26 
GeneralReason for my vote of 3 This is trivial for people with a bi... Pin
Bigdeak30-Jun-10 22:11
Bigdeak30-Jun-10 22:11 
Reason for my vote of 3
This is trivial for people with a bit experience.
But for beginners it's a nice tip.
You should name it "Replace specified chars in string" or something in my oppinion.
GeneralReason for my vote of 1 That's not whitespace, that's just s... Pin
Jouke van der Maas29-Jun-10 8:45
Jouke van der Maas29-Jun-10 8:45 
GeneralVery True comment Niklas - The string value is an example of... Pin
DecodedSolutions.co.uk28-Jun-10 3:18
DecodedSolutions.co.uk28-Jun-10 3:18 
GeneralThis can be done in-place at a fraction of the cpu usage. Pin
Niklas L28-Jun-10 1:57
Niklas L28-Jun-10 1:57 
GeneralReason for my vote of 1 trivial Pin
BugByter26-Jun-10 10:19
BugByter26-Jun-10 10:19 
GeneralReason for my vote of 5 wow ;} Pin
radioman.lt25-Jun-10 21:40
radioman.lt25-Jun-10 21:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.