奇怪的行为字符串.修剪方法
本文关键字:字符串 修剪 方法 | 更新日期: 2023-09-27 18:18:21
我想从字符串中删除所有空格(只有' '
和''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()
工作完美。为什么会有这种行为?如何使用Trim()
方法从字符串中删除''t
' ?
字符串。Trim方法只处理字符串
开头和结尾的空白。所以你应该使用String。替代方法
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"
Trim只删除字符串开头和结尾的空白。因此,因为第一个字符串以'r'n结束,这显然不被认为是空白,Trim没有看到任何要删除的内容。可以使用Replace替换字符串中的空格和制表符。例如:test.Replace(" ", "").Replace("'t", "");
Trim()
删除边缘字符。似乎您想要删除字符串中的任何位置的字符,您可以这样做:
test.Replace("'t", null);
当您传递null
作为替换值时,它只是删除旧值。从MSDN:
如果newValue为null,所有出现的oldValue都被删除。
还要注意,您可以链接调用Replace
:
test = test.Replace("'t", null).Replace(" ", null);