奇怪的行为字符串.修剪方法



我想从字符串中删除所有空格(只有' ''t', 'rn'应该保留)。但是我有问题。

的例子:如果我有

string test = "902322trn900657trn10421trn";
string res = test.Trim(); // res still "902322trn900657trn10421trn" 
res = test.Trim('t'); // res still "902322trn900657trn10421trn" 

但是如果我有

string test = "902322t";

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

字符串。Trim方法只处理字符串

开头和结尾的空白。

所以你应该使用String。替代方法

string test = "902322trn900657trn10421trn";
string res = test.Replace("t", String.Empty); // res is "902322rn900657rn10421rn" 

Trim只删除字符串开头和结尾的空白。因此,因为第一个字符串以rn结束,这显然不被认为是空白,Trim没有看到任何要删除的内容。可以使用Replace替换字符串中的空格和制表符。例如:test.Replace(" ", "").Replace("t", "");

Trim()删除边缘字符。似乎您想要删除字符串中的任何位置的字符,您可以这样做:

test.Replace("t", null);

当您传递null作为替换值时,它只是删除旧值。从MSDN:

如果newValue为null,所有出现的oldValue都被删除。

还要注意,您可以链接调用Replace:

test = test.Replace("t", null).Replace(" ", null);

最新更新