문제

I want to remove all white spaces from string variable which contains a sentence. Here is my code:

string s = "This text contains white spaces";
string ns = s.Trim();

Variable "sn" should look like "Thistextcontainswhitespaces", but it doesn't(method s.Trim() isn't working). What am I missing or doing wrong?

도움이 되었습니까?

해결책

The method Trim usually just removes whitespace from the begin and end of a string.

string s = "     String surrounded with whitespace     ";
string ns = s.Trim();

Will create this string: "String surrounded with whitespace"

To remove all spaces from a string use the Replace method:

string s = "This text contains white spaces";
string ns = s.Replace(" ", "");

This will create this string: "Thistextcontainswhitespaces"

다른 팁

Try this.

s= s.Replace(" ", String.Empty);

Or using Regex

s= Regex.Replace(s, @"\s+", String.Empty);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top