views:

298

answers:

5

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("-", "");
+8  A: 

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

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

Charles Bretana
Hence, the name "trim" :-) +1
Chris Dwyer
A: 

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().

David Seiler
+2  A: 

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.

Eric Smith
A: 

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.

AnthonyWJones
A: 

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

pawan jain