C# 奇怪的行为字符串.Trim方法

C# 奇怪的行为字符串.Trim方法,c#,string,special-characters,trim,C#,String,Special Characters,Trim,我要删除所有空格。只有“”和“\t”,字符串中的“\r\n”应该保留。但我有问题 例如: 如果我有 string test = "902322\t\r\n900657\t\r\n10421\t\r\n"; string res = test.Trim(); // res still "902322\t\r\n900657\t\r\n10421\t\r\n" res = test.Trim('\t'); // res still "902322\t\r\n900657\t\r\n10421\t\

我要删除所有空格。只有“”和“\t”,字符串中的“\r\n”应该保留。但我有问题

例如: 如果我有

string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
string res = test.Trim(); // res still "902322\t\r\n900657\t\r\n10421\t\r\n" 
res = test.Trim('\t'); // res still "902322\t\r\n900657\t\r\n10421\t\r\n" 
但如果我有

string test = "902322\t";
修剪得很好。为什么会有这种行为?如何使用Trim方法从字符串中删除“\t”?

方法只处理字符串开头和结尾的空格

所以你应该使用

修剪删除边缘字符。您似乎希望删除字符串中的任意位置的字符,可以通过以下方式执行此操作:

test.Replace("\t", null);
当您传递null作为替换值时,它只是删除旧值。发件人:

如果newValue为null,则删除所有出现的oldValue

还请注意,您可以链接调用以替换:


Trim仅删除字符串开头和结尾的空格。因此,由于第一个字符串以\r\n结尾,这显然不被视为空白,Trim没有看到任何要删除的内容。可以使用“替换”替换字符串中的空格和制表符。例如: test.Replace、.Replace\t、

否,test.Trim将返回902322\t\r\n900657\t\r\n10421。我刚在csharppad.com上试过。请给出一个简短但完整的程序来演示这个问题-我怀疑你是在误诊。
test.Replace("\t", null);
test = test.Replace("\t", null).Replace(" ", null);