§ ITPOW >> 文档 >> C#

试试 StartsWith 这东西

作者:vkvi 来源:ITPOW(原创) 日期:2010-6-9

C# 的 string 实例有个方法是 StartsWith 用来判断 string 实例是否是以某个子字符串开始。注意 Start 后面有个 s。

string str = "ITPOW";
bool b = str.StartsWith("千"); // true
bool b2 = str.StartsWith("一"); // false

问题一、大小写敏感吗?

默认敏感。要让大小写不敏感,可指定第二个参数,比如:

string str = "cftea";
bool b = str.StartsWith("C", StringComparison.CurrentCultureIgnoreCase); // true

关于第二个参数,可参见 C# 字符串比较-Compare

问题二、StartsWith("") 结果

如果 StartsWith 的第一个参数是零长度字符串,那么,它永远都返回 true。

string str = "cftea";
bool b = str.StartsWith(""); // true
相关文章