C# Trim() vs replace()
Solution 1
Trim()
and Replace()
do not serve the same purpose.
Trim()
removes all whitespace characters from the beginning and end of the string. That means spaces
, tabs
, new lines
, returns
, and other assorted whitespace characters.
Replace()
only replaces the designated characters with the given replacement. So Replace(" ", string.empty)
will only replace spaces with empty strings. Replace() also replaces all instances of the designated string with the given replacement, not just those at the beginning and end of the string.
Solution 2
String.Replace
will remove all (and only) space characters, and String.Trim
will remove all whitespace characters from the beginning and the end of the string, not ones in the middle.
var tmp = " hello world \t";
var res1 = tmp.Trim(); // "hello world"
var res2 = tmp.Replace(" ", String.Empty); // "helloworld\t"
Solution 3
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.
Example:
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: if you want remove just single characters from start or/and end of string use Trim()
otherwise call Replace()
.
Solution 4
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)
SARAVAN
Updated on August 22, 2020Comments
-
SARAVAN over 3 years
In a C#
string
if we want to replace" "
in a string tostring.empty
, is it fine to usestringValue.Trim()
orstringValue.replace(" ", string.empty)
. Both serve the same purpose. But which one is better? -
Nick Zimmerman over 9 yearsI am well aware of the overloads for Trim(). It still does not make Trim() and Replace() equivalent. They do not serve the same purpose.
-
bugged87 over 9 yearsTrim() can remove non-whitespace characters as well. A method overload takes an array of characters to trim.