a common misunderstanding of string.Trim functions

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值