You probably knew that you can use the String.Trim method to remove whitespace from the start and end of a C# string. Unfortunately, the Trim method does not remove whitespace from the middle of a string.
Given this example:
string text = " My testnstringrn ist quite long "; string trim = text.Trim();
The ‘trim’ string will be:
“My testnstringrn ist quite long” (31 characters)
Another approach is to use the String.Replace method, but that requires you to remove each individual whitespace character via multiple method calls:
string trim = text.Replace( " ", "" ); trim = trim.Replace( "r", "" ); trim = trim.Replace( "n", "" ); trim = trim.Replace( "t", "" );
The best approach is to use regular expressions. You can use the Regex.Replace method, which replaces all matches defined by a regular expression with a replacement string. In this case, use the regular expression pattern “s”, which matches any whitespace character including the space, tab, linefeed and newline.
string trim = Regex.Replace( text, @"s", "" );
The ‘trim’ string will be:
“Myteststringisquitelong” (23 characters)
very good
“Unfortunately, the Trim method does not remove whitespace from the middle of a string.”
How is that unfortunate? a string with no whitespace at the beginning or end is FAR FAR more useful than a string with all whitespace removed.
“How is that unfortunate? a string with no whitespace at the beginning or end is FAR FAR more useful than a string with all whitespace removed.”
Well, that depends on the application, doesn’t it?
It’s unfortunate because it would’ve been nice for the Trim method to handle all cases. e.g.,
[Flags]
public enum TrimOptions
{
Start = 0x01,
Middle = 0x02,
End = 0x04,
}
This is a nice and simple example
you could use
string trim = Regex.Replace(text, @”s+”, ” “).Trim();
if you want to keep the words seperated with spaces
e.g.
for this example we will get :
My test string is quite long
Cheers Adam. That was helpful 🙂
Thanks…It helped
It worked for me too. Thank you very much – I couldn’t understand this.
Hi,
How to detect two white space in text altogether so that we can remove it in C#
Thanks very much.
I want something like this:
If below is my string
ROBERT EATS MEAT.
Write a C# Code to Extract the first Letter, and add it to the last word. e.g i want to return
RMEAT.
How do i do that?
thanks in advance
I think a better approach is to use the Split function and throw away the blank tokens. Then you can re-concatenate the tokens with or without a single space in between (as in, normal sentence spacing).
Thanks so much. I’ve been trying to clean MAC addresses so that it doesn’t matter if you hand it “0011223344”, or “00:11:22:33:44”, or “00 11 22 33 44”.
My button_click code…
string macString = textBox1.Text.Replace( “:”, “” );
macString = macString.Replace(“-“, “”);
macString = macString.Replace(” “, “”);
WakeFunction(macString);
it is better solution,
if we have string s:
StringBuilder sb = new StringBuilder(s);
foreach (char wc in in string.WhitespaceChars)
sb.Replace(wc, ‘ ‘); // replace with space
s = sb.ToString();
cause String.WhitespaceChars may be unavailable
use this array:
string[] whitespaceChars = new string[] {
char.ConvertFromUtf32(9),
char.ConvertFromUtf32(10),
char.ConvertFromUtf32(11),
char.ConvertFromUtf32(12),
char.ConvertFromUtf32(13),
char.ConvertFromUtf32(32),
char.ConvertFromUtf32(133),
char.ConvertFromUtf32(160),
char.ConvertFromUtf32(5760),
char.ConvertFromUtf32(8192),
char.ConvertFromUtf32(8193),
char.ConvertFromUtf32(8194),
char.ConvertFromUtf32(8195),
char.ConvertFromUtf32(8196),
char.ConvertFromUtf32(8197),
char.ConvertFromUtf32(8198),
char.ConvertFromUtf32(8199),
char.ConvertFromUtf32(8200),
char.ConvertFromUtf32(8201),
char.ConvertFromUtf32(8202),
char.ConvertFromUtf32(8203),
char.ConvertFromUtf32(8232),
char.ConvertFromUtf32(8233),
char.ConvertFromUtf32(12288),
char.ConvertFromUtf32(65279)};
for previous post
one line:
string macString = textBox1.Text.Replace( “:”, “” ).Replace(“-“, “”).Replace(” “, “”);
@SKIPP: So you are claiming your 20 lines of code are better than this article’s one line? Regex works great and is relatively fast. Also note that your method is wholly inefficient because it scans the source string for every whitespace character, instead of the other way around.
yes, cause “[ trnvf]” not the only one’s symbols which can be interpreted as whitespace
http://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes
public static class StringExtensions
{
public static string StripPunctuation(this string s)
{
var sb = new StringBuilder();
foreach (char c in s)
{
if (!char.IsPunctuation(c))
sb.Append(c);
}
return sb.ToString();
}
public static string StripWhiteSpace(this string s)
{
var sb = new StringBuilder();
foreach (char c in s)
{
if (!char.IsWhiteSpace(c))
sb.Append(c);
}
return sb.ToString();
}
}
hello bacha log
i am designing a filter system for my website and there is a text box in the filter for full user name i m using trim method for removing white spaces but it’s only working for single name not full name
like if i write
john xyz it works
or john xyz it works
but when i write
john works it doesn’t work
can any one help in this
the post is not showing the white spaces i have entered in my example
i wanna say that
if i give white spaces before full name
ex.
if i give white space before john xyz it’s not working
can any one tell me how to remove leading white spaces for full name like my example
use regex! (regular expressions)
i have a string like abc.wav after wave there is series of empty spaces in it ,i have tried every method to reomeve this ,but failed so far..actually this string come from Socket..n i am recieving this string n trin to remove spaces but still no success ,any help would be appreciated.
@cayber: It’s possible the characters after “abc.wav” are not normal whitespace (maybe they are control characters) in which case the Trim method won’t work, and you would need to manually remove non-alphabetical and non-numeric characters.
Thanks.. very much Adam for e.g of if you want to keep the words seperated with spaces
how do i do ??
if i want to keep the words seperated with spaces
using Split,Trim.
Great tutorial.. i have an question that if i have a string “This is my India.” and wants to remove all the ‘i’ character from it and the final string is “Ths s my nda” . How to do this ?
Thanks in advance …
@HFM Solutions: Use the string.Replace() method, but be sure to pass “i” as a string and not the character ‘i’:
string s = “This is my India.”;
s = s.Replace( “i”, null );
Console.WriteLine( s );
Output: Ths s my Inda.
string sourceString = “This is my India.”;
string stringToReplace = “i”;
string outputString = sourceString.Replace(stringToReplace.ToLower(), null).Replace(stringToReplace.ToUpper(), null);
Console.WriteLine(outputString);
I have found Regex to be quite slow. A less pretty but faster solution could look like this:
while (v.IndexOf(” “) > 0)
v = formatted_v.Replace(” “, ” “);
leaving only single spaces.
StringBuilder would be better than String.
Or you could put together a clever little recursive using IndexOf and Remove.
value = Regex.Replace(value, “\\s+”, ” “);
Code above will leave only single spaces in between words and remove any whitespace character.
private void button1_Click(object sender, EventArgs e)
{
string hh = textBox1.Text;
string fateh;
string[] Split = hh.Split(new Char[] { ‘ ‘ });
//SHOW RESULT
for (int i = 0; i < Split .Length; i++)
{
fateh += Convert.ToString(Split[i]);
}
textBox1.Text = fateh;
}
Thanks Dear,
I like your solution of text.replace(” “,””);
This is really helped me.
new string(text.Where(x => !char.IsWhiteSpace(x)).ToArray())
Forgot to escape s in @”s”, so it should be:
string trim = Regex.Replace( text, @”\s”, “” );
Hello People,
What if I have text like this one:
something
this text
something else
and I want to replace with:
something
this text
something else
I want to keep the text before and after intact but want to add something before the middle text and after with the middle text also intact.
I have this regular expression:
Search:
something
[^‰\r\n]*
something else
replace:
something
? ? ? ? ? ?
something else
What regular expression could I use to maintain the text in the middle?
Thanks!
For anyone interested in speed, this blog posting benchmarks the fastest way to Trim() strings:
http://cc.davelozinski.com/c-sharp/fastest-way-to-trim-strings
using multiple techniques.