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