Search code examples
c#stringreplacetrim

C# Trim() vs replace()


In a C# string if we want to replace " " in a string to string.empty, is it fine to use stringValue.Trim() or stringValue.replace(" ", string.empty). Both serve the same purpose. But which one is better?


Solution

  • 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.