奇怪的行为string.Trim方法

isx*_*ker -5 c# string trim special-characters

我想从字符串中删除所有空格(仅限' ''\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" 
Run Code Online (Sandbox Code Playgroud)

但如果我有

string test = "902322\t";
Run Code Online (Sandbox Code Playgroud)

Trim()工作完美.为什么会这样?如何'\t从字符串使用Trim()方法中删除' ?

Eug*_*kal 5

String.Trim方法仅处理字符串开头和结尾的空格

所以你应该使用String.Replace方法

string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
string res = test.Replace("\t", String.Empty); // res is "902322\r\n900657\r\n10421\r\n" 
Run Code Online (Sandbox Code Playgroud)