用最常用的方法无法清除空白区域

Ler*_*ica 0 c# string

情况就是这样 - 我需要使用a的Text属性,ToolStripItem我需要在此之前清除字符串中的所有空格.但是我尝试了三种非常常见的(在我看来)场景,它们都没有返回没有空格的字符串.这是我尝试过的:

string tempBtnText = tempItem.Text;
Run Code Online (Sandbox Code Playgroud)

tempBtnText在我使用Text属性的方法中定义.我觉得这样比较容易.然后我尝试了那些:

tempBtnText.Replace(" ", String.Empty);
tempBtnText = Regex.Replace(tempItem.Text, @"^\s*$\n", string.Empty);
string tempBtnTexts = Regex.Replace(tempItem.Text, @"\s+", "");
Run Code Online (Sandbox Code Playgroud)

所有这些都返回了原始形式的字符串(带有空格).删除空格的唯一方法是使用此方法:

public string RemoveWhitespace(string input)
{
    return new string(input.ToCharArray()
        .Where(c => !Char.IsWhiteSpace(c))
        .ToArray());
}
Run Code Online (Sandbox Code Playgroud)

我在这里发现了类似的帖子SO.但我真的不明白为什么上述所有方法都不起作用.我开始认为与我正在使用ToolStripItemText属性这一事实有关,但正如我刚才所说,我声明了我自己的字符串变量,该变量取得了Text属性的值.

我不知道.有人能告诉我,这种行为的原因是什么.并不是说使用另一种方法清除空白区域是一个很大的问题,但是不工作的选项更加紧凑和可读,我想尽可能使用其中一种方法.

aba*_*hev 5

字符串是不可变的,这意味着任何操作都会生成一个新实例,因此您需要将任何方法结果分配回输入:

string input = "...";
intput = intput.Replace(x, y);
Run Code Online (Sandbox Code Playgroud)