C为什么要用StartsWith而不是Substring进行字符串匹配?
字符串的截取匹配操作在开发中非常常见,比如下面这个示例:我要匹配查找出来字符串数组中以"abc"开头的字符串并打印,我下面分别用了两种方式实现,代码如下:
using System;
namespace ConsoleApp23{ class Program { static void Main(string[] args) { string[] strs = new string[] { "abc123" , "abc456" ,"ab123","a12345" };
foreach (var str in strs) { if (str.Substring(0, 3) == "abc") { Console.WriteLine(str); } } Console.WriteLine();
foreach (var str in strs) { if (str.StartsWith("abc")) { Console.WriteLine(str); } }
Console.ReadKey(); } }}
运行结果如下:
诚然,两种方法都输出了正确的结果。
那么既然,两种方式都能实现,这两种方法有没有什么区别呢?当然有的,而且大多数时候,一个老练的程序员都会用StartsWith而不是Substring,为什么呢?
往下看,我把数据源修改下:
static void Main(string[] args) { string[] strs = new string[] { "abc123" , "abc456" ,"ab123","a12345" ,"abc","ab"};
foreach (var str in strs) { if (str.Substring(0, 3) == "abc") { Console.WriteLine(str); } } Console.WriteLine();
foreach (var str in strs) { if (str.StartsWith("abc")) { Console.WriteLine(str); } }
Console.ReadKey(); }
运行后,方法一直接崩了,但是方法2则可以正确运行出来结果
看一下Substring的用法解释:startIndex 加 length 指示不在此实例内的位置。- 或 - startIndex 或 length 小于零。,所以当字符串小于你要截取的长度时,你如果没用try catch去捕获异常,代码就崩溃了.
[SecuritySafeCritical] public String Substring(int startIndex, int length);
所以,我们需要慎用Substring,如果非要用,一定需要进行异常处理。