.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
a common misunderstanding of string.Trim functions

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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.




相关文章

相关软件