views:

125

answers:

10

My variable looks like:

name = "Lola                                 "; // notice the whitespace

How can I delete the whitespace at the end to leave me with just "Lola"?


Thank you all, but .Trim() don't work to me.

I read the text from a file, if that is any help.

+16  A: 

use Trim().

 string name = "Lola       "
 Console.WriteLine(name.Trim()); // puts out 'Lola'
Jan Jongboom
A: 

Use the Trim() method.

ho1
+1  A: 

Check out string.Trim()

http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx

Rohan West
+7  A: 

If the space will always be at the end of the string, use:

name = name.TrimEnd();

If the space may also be at the beginning, then use:

name = name.Trim();
ICR
A: 

Just use

string.Trim()

to remove all spaces from your string;

string.TrimEnd()

to remove spaces from the end of your string

string.TrimStart()

to remove spaces from the start of your string

Johnny
A: 

use Trim(). So u can get only "Lola"

LiteK
A: 

Or is this what you meant to do?

string name = "Lola ...long space...";
Console.WriteLine(name.Substring(0, name.IndexOf(" ") - 1)); // puts out 'Lola'
Geert Immerzeel
+5  A: 

Trim doesn't change the string, it creates a new trimmed copy. That is why it seems like name.Trim(); isn't doing anything -- you are throwing away the results.

Instead, use name = name.Trim(); as ICR suggests.

Ben Voigt
+2  A: 

The answer is .Trim(). Note that since strings are immutable, you have to assign the result of the operation:

name = "Lola                                 ";
name.Trim();  // Wrong: name will be unchanged
name = name.Trim();  // Correct: name will be trimmed
Daniel Rose
A: 

If you wanted to remove all spaces anywhere in the string, you could use Replace()

string name = "   Lola Marceli    ";
Console.WriteLine(name.Replace(" ", "")); // puts out 'LolaMarceli'
Edward Leno