Wednesday, 20 July 2011

Tips of using Trim

Trim() can remove line breaks and space in the same time. For example:


string s = "hello world.\r\n\r\n";
string ret = s.Trim();
Console.WriteLine(ret);

result: "hello world.”  //line breaks removed

string s = "hello world.  \r\n\r\n";
string ret = s.Trim();
Console.WriteLine(ret);

result: "hello world.” //line breaks and trailing space being removed by one Trim()

Sometimes I have my message concatenated in a string:

msg = msg + "; custom message 1";
...
msg = msg + "; custom message 2";
...
msg = msg + "; custom message 3";

In the end, I want to remove the '; ' from the beginning of msg to look better, I can do the following:

string ret = msg.Trim(new char[]{';',' '});

The beauty is: even both custom message 1 and custom message 2 are empty, the msg will look like:

"; ; custom message 3"

After single trimming, you can still get "custom message 3", and you don't have to check if the msg is empty every time.


No comments:

Post a Comment