a common misunderstanding of string.Trim functions

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航