1

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("-", "");
2
  • What would 1 Jan 1999 look like in the format: 1999-01-01 ? Commented Sep 1, 2009 at 15:12
  • Depends on what you do with it. In SQL Server any string passed in YYYY-MM-DD HH:MM:SS format translates, e.g: '1999-01-01 12:00:00' will be 1 Jan 1999 @ 12AM. Your localization doesn't matter in that case. Commented Sep 1, 2009 at 15:26

5 Answers 5

8

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hence, the name "trim" :-) +1
1

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.

Comments

0

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.