سؤال

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