String.split

本文深入探讨了Java中String.split方法的使用细节,特别是如何通过指定限制参数来获取包含空字符串的结果数组,避免了不必要的自定义分割函数实现。
String.split(String reg)这个方法一点不陌生。经常用:
"a|b|c".split("\\|")

结果是:
["a","b","c"]

但是,如果改一下输入参数呢?
"a|b|".split("\\|")

结果是:
["a","b"]


这是你想要的吗?如果是,我不废话了。如果不是,那怎么办呢?
反正这不是我想要的,我想要:
["a","b",""]

我绕了一大圈子:我去找apache commons中有没有这样的实现,没有找到。于是我开始自己写一个:
static String[] newsplit(String str) {
if (str == null || str.length() == 0) {
return new String[0];
}

List<Integer> indexes = new LinkedList<Integer>();
indexes.add(-1);
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '|') {
indexes.add(i);
}
}

indexes.add(str.length());

List<String> list = new LinkedList<String>();
for (int i = 0; i < indexes.size()-1; i++) {
list.add(str.substring(indexes.get(i)+1,indexes.get(i+1)));
}

return list.toArray(new String[0]);
}

我自以为可以了。于是开始测试这个方法,我用了一个复杂点的例子"a||b|c|"。还好JUnit绿了。好兴奋啊。这时候,我想不明白为何JDK不提供这么简单的实现,于是我又试了下:
"a||b|c|".split("\\|")
结果是:
["a","","b","c"]

结尾的那一项还是没了,但是中间的那个空字符串竟然还在。不会吧!难道?!我打开了jdk的api的[url=http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html]页面[/url]。看到了还有这样一个方法:Pattern.split(CharSequence,int)。然后看到了这样一段话:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

然后,我试了下
"a||b|c|".split("\\|",-1)
结果就是我想要的。一刹那我想撞墙。为什么,一开始不仔细在jdk中先看看啊。

反思:
1>当你遇到一个问题,最优的解决方式就在最近的地方。
2>熟悉api是非常重要的。
3>不要手贱。
### C# 中 `String.Split` 方法的使用和示例 在 C# 编程中,`String.Split` 是一个常用的方法,用于将字符串按照指定的分隔符拆分为多个子字符串。该方法存在于 `string` 类中,因此可以在任何字符串上调用它。`String.Split` 的语法可以分为两类:一类是以字符(`char`)作为分隔符,另一类是以字符串(`string`)作为分隔符[^4]。 #### 使用字符作为分隔符 当使用字符作为分隔符时,可以通过以下几种方式调用 `Split` 方法: - **根据指定的分隔字符将字符串拆分为子字符串**: ```csharp string str = "长亭外-古道边-芳草碧连天"; string[] arr = str.Split('-'); foreach (string s in arr) { Console.WriteLine(s); } ``` 此代码将字符串 `str` 按照 `'-'` 分隔符拆分成多个子字符串,并输出每个子字符串[^2]。 - **根据指定的分隔字符将字符串拆分成最大数量的子字符串**: ```csharp string str = "apple,banana,orange,grape"; string[] result = str.Split(new char[] { ',' }, 2); ``` 上述代码将字符串 `str` 拆分成最多两个部分。 - **根据指定的分隔字符和选项将字符串拆分为子字符串**: ```csharp string str = "a,,b,c"; string[] result = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ``` 此代码将忽略空条目,结果数组只包含 `"a"`, `"b"`, `"c"`。 - **基于指定的分隔字符和(可选)选项将字符串拆分为最大数量的子字符串**: ```csharp string str = "one two three four five"; string[] result = str.Split(new char[] { ' ' }, 3, StringSplitOptions.None); ``` 该代码将字符串按空格分割为最多三个部分。 #### 使用字符串作为分隔符 除了字符,还可以使用字符串作为分隔符来拆分字符串: - **根据指定的分隔字符串将字符串拆分为子字符串**: ```csharp string input = "hello world welcome to C#"; string[] parts = input.Split(new string[] { " " }, StringSplitOptions.None); ``` - **根据指定的分隔字符串将字符串拆分成最大数量的子字符串**: ```csharp string input = "apple|banana|orange|grape"; string[] parts = input.Split(new string[] { "|" }, 2, StringSplitOptions.None); ``` - **基于指定的分隔字符串和(可选)选项将字符串拆分为子字符串**: ```csharp string input = "data1,,data2,data3"; string[] parts = input.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); ``` - **基于指定的分隔字符串和(可选)选项将字符串拆分为最大数量的子字符串**: ```csharp string input = "item1;item2;item3;item4"; string[] parts = input.Split(new string[] { ";" }, 3, StringSplitOptions.None); ``` 上述示例展示了如何灵活地使用 `String.Split` 方法来处理不同场景下的字符串分割需求。通过选择适当的重载形式,可以精确控制拆分行为,例如限制返回的子字符串数量或去除空条目。 此外,`String.Split` 方法常用于解析用户输入的数据,例如从全名中提取姓氏、名字和中间名首字母等操作。这种情况下,`Split` 方法能够帮助程序更有效地处理和分析字符串内容[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值