Class System.String is of no doubt the most commonly used class in .Net framework (as in any other programming environment) as long as text processing is concerned. String class supplies three methods with respect to trimming, namely Trim, TrimStart, and TrimEnd respectively. As clearly stated in the SDK, this familiy of methods remove all occurrentces of a set of characters specified in the parameters. Let's take TrimStart as example, a typical usage of this method is as follow:
string word = "prefixword";
string prefix = "prefix";
string left = word.TrimStart(prefix.ToCharArray());
and the value of left will be "word" after execution.
However, this might make one think that Trim method actually remove the specified string (prefix in the above example) from a string instance. For example, string fullname = "folder\\file";
string folder = "folder\\";
string filename = fullname.TrimStart(folder.ToCharArray());
This snippet originally intends to remove "folder\\" from fullname. But what will filename be finally? Not “file”, but “ile”. That's because each character of “folder\\f” falls in the character set of folder and is therefore trimmed while “i” does not. Look at the following example: string name1 = "accabaaxniy";
string name2 = "abc";
string name3 = name1.TrimStart(name2.ToCharArray());
Well, name3 will finally have the value "xniy".
Now its clear what Trim methods can do can what they can't. Then how to remove a leading or trailing string from another one? Let's take leading string as example, it applies to trailing string as well. Look at the second example, where fullname begins with folder and we want to remove this leading string. We can use Remove method like:
string fullname = "folder\\file";
string folder = "folder\\";
string filename = fullname.Remove(0, folder.Length);
It'll work now, but pls note, make sure that one string really begins with another, otherwise the Remove method will never lead to what you want.