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

How to avoid Blank space insertion at the beginning of the String in Java while using Split() function

这是代码片段。

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

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

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

这里到底发生了什么?

IdeOne Link

我试过你的代码,没问题。

我认为可能 白色 space 错误 导致了问题。

使用trim()避免此类错误。

    String s="google";
    String[] s1=s.trim().split("");
    System.out.println(s1[0]);
    System.out.println(s1.length);

根据非单词边界拆分您的输入。

string.split("\B");

\B 匹配两个非单词字符或两个单词字符。

DEMO

根据下面的正则表达式拆分。

string.split("(?<!^)(?:\B|\b)(?!$)");

String.split() 方法在 Java 7(由 IdeOne 使用)和 Java 8(可能被一些评论者和回答者使用)中表现不同。 Java 8 JavaDoc documentation for String.split() 中,是这样写的:

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.

所以,根据Java8,"google".split("")等于["g","o","o","g","l","e"]

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

(Java7和Java8数组末尾的空字符串都被去掉了。)

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