中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > .NET > 临时文章
a common misunderstanding of string.Trim functions
作者:未知 时间:2004-12-16 12:12 出处:Blog 责编:chinaitpower
              摘要:暂无

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.

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有