16

在 C#中string,如果我们想将" "字符串替换为string.empty,是否可以使用stringValue.Trim()or stringValue.replace(" ", string.empty)。两者都有相同的目的。但是哪一个更好呢?

4

8 回答 8

41

Trim()并且Replace()不用于相同的目的。

Trim()从字符串的开头和结尾删除所有空白字符。这意味着spaces, tabs, new lines,returns和其他各种空白字符

Replace()只用给定的替换替换指定的字符。所以Replace(" ", string.empty)只会用空字符串替换空格。Replace() 还用给定的替换替换指定字符串的所有实例,而不仅仅是字符串开头和结尾的那些。

于 2013-09-19T18:48:02.270 回答
15

String.Replace将删除所有(且仅)空格字符,String.Trim并将删除字符串开头和结尾的所有空格字符,而不是中间的空格字符。

var tmp = "  hello world  \t";
var res1 = tmp.Trim(); // "hello world"
var res2 = tmp.Replace(" ", String.Empty); // "helloworld\t"
于 2013-09-19T18:46:51.183 回答
2

Trim can eliminate whitespace and non-whitespace characters only from start and/or end of strings. Replace can remove substring from any places in your string.

例子:

Console.WriteLine("{{Hello World!:)".Trim('{',':',')'));  //output: Hello World
Console.WriteLine("{{Hello%World!:)".Trim('{', '%', ':',')'));  //output: Hello%World

Console.WriteLine("{{Hello World!:)".Replace("{{", string.Empty)
                                    .Replace(":)",string.Empty));  //output: Hello World

Console.WriteLine("{{Hello%World!:)".Replace("{{", string.Empty)
                                    .Replace("%", string.Empty)
                                    .Replace(":)",string.Empty));  //output: Hello World

TL; DR:如果您只想从字符串的开头或/和结尾删除单个字符,请使用Trim()否则调用Replace().

于 2018-08-21T10:49:08.597 回答
1
char [] chartrim={'*'};
string name=Console.ReadLine(); //input be *** abcd **
string result= name.Trim(chartrim);
Console.WriteLine(result);

In this case output will be abcd. Trim only remove the whitespace or the symbol which u want to trim from beginning and end of the string.

But in case of string.Replace() is that it will replace the string which you want to get replaced for ex.

string name=Console.ReadLine(); //input be mahtab alam
string str2="khan";
string result= name.Replace("alam",str2);
Console.WriteLine(result);

In this case o/p will be mahtab khan.

If you want to remove space in between the strings (in this case output will be mahtabalam)

string name=Console.ReadLine(); //input be mahtab alam
string result= name.Replace(" ",string.Empty);
Console.WriteLine(result)
于 2016-09-12T13:35:57.190 回答
0

String.Trim()将仅删除前导和尾随空格。所以你必须使用String.Replace()你的目的。

于 2013-09-19T18:46:54.013 回答
0

Trim 消除了前导和尾随空格,而 Replace 更改了字符串数据。它将一个子字符串的所有出现更改为另一个子字符串。它还处理字符替换。

于 2013-09-19T18:47:10.253 回答
0

Replace 将替换它在字符串中的任何位置。Trim 只会从字符串的开头和结尾修剪空白......所以他们实际上做了不同的事情。

于 2013-09-19T18:47:23.770 回答
0

as Nick Zimmerman said Trim() removes all whitespace characters from the beginning and end of the string. But you can use it in a different way :

Trim(char[] trimChars) which removes all leading and trailing occurrences of a set of characters specified in the array passed in as a parameter.

Check MSDN

于 2014-02-21T10:07:55.210 回答