Mr. Smith
Mr. Smith

Reputation: 5558

Trimming a string using an array of characters using C#

When you use the Trim() method on a string object, you can pass an array of characters to it and it will remove those characters from your string, e.g:

string strDOB = "1975-12-23     ";
MessageBox.Show(strDOB.Substring(2).Trim("- ".ToCharArray()));

This results is "75-12-23" instead of the expected result: "751223", why is this?

Bonus question: Which one would have more overhead compared to this line (it does exactly the same thing):

strDOB.Substring(2).Trim().Replace("-", "");

Upvotes: 1

Views: 1534

Answers (5)

pawan jain
pawan jain

Reputation: 139

Trim removes only from start and end. Use Replace if u want to remove from within the string.

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189457

Others have answered correctly Trim only trims characters from the start and end of the string. Use:-

Console.WriteLine( strDOB.Substring(2, 8).Replace("-","") )

This assumes a fixed format in the original string. As to performance, unless you are doing a million of these I wouldn't worry about it.

Upvotes: 0

Eric Smith
Eric Smith

Reputation: 5392

From MSDN:

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

I guess that's self-explanatory.

Upvotes: 1

David Seiler
David Seiler

Reputation: 9705

Trim only removes characters from the beginning and end of the string. Internal '-' characters will not be removed, any more than internal whitespace would. You want Replace().

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146499

Cause the trim function only trims characters from the ends of the string.

use Replace if you want to eliminate them everywhere...

Upvotes: 8

Related Questions