gpt4 book ai didi

java - 使用 Split() 函数时如何避免在 Java 中的字符串开头插入空格

转载 作者:行者123 更新时间:2023-11-30 08:12:48 25 4
gpt4 key购买 nike

这是代码片段。

public static void main(String...strings){
String s="google";
String[] s1=s.split("");
System.out.println(s1[0]);
System.out.println(s1.length);
}

我正在尝试围绕每个字符拆分 String 。但问题是在拆分数组的开头引入了拆分空格。这给了我输出长度 7 而不是 6。并且因为它不能有尾随空格,因为这里的拆分将作为 split("", 0) 传递,所以它必须在开始为了测试我打印了 s1[0] 并且它确实给出了空格。

我的问题是如何避免这样的问题。我需要使用拆分。

这里到底发生了什么?

IdeOne Link

最佳答案

String.split() 方法在 Java 7(由 IdeOne 使用)和 Java 8(可能由一些评论者和回答者使用)中表现不同。在 String.split() 的 Java 8 JavaDoc 文档中,写了以下内容:

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

因此,根据 Java 8,"google".split("") 等于 ["g","o","o","g","l","e"].

Java 7 文档中没有这个注释,事实上,在 Java 7 中,"google".split("") 似乎等于 ["", "g","o","o","g","l","e"]

(在 Java 7 和 Java 8 中,数组末尾的空字符串都被删除了。)

最好的解决方案似乎是只添加代码以忽略第一个字符串(如果它为空)。 (请注意,当您的输入包含多个单词时,另一个答案中建议的 split("\\B") 解决方案会产生意想不到的结果。)

关于java - 使用 Split() 函数时如何避免在 Java 中的字符串开头插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30252318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com