开发者

C# delete space from variable [duplicate]

This question already has answers here: 开发者_JAVA技巧 How to remove leading and trailing spaces from a string (9 answers) Closed 7 years ago.

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.


use Trim().

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


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();


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.


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


Check out string.Trim()

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


Use the Trim() method.


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


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


Or is this what you meant to do?

string name = "Lola ...long space...";
Console.WriteLine(name.Substring(0, name.IndexOf(" ") - 1)); // puts out 'Lola'


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜