简体   繁体   中英

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

Here is the code Snippet.

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

I'm trying to split the String s around each character. But the problem is while splitting a blank space is getting introduced at the begining of the splitted array. Which is giving me output length 7 instead of 6. and since it can't have trailing spaces as split here will be getting passed as split("", 0) , so it has to be at the beginning To test i printed s1[0] and its giving blank space indeed.

My question is how to avoid such problem. I need to use split.

What is actually happening here.?

IdeOne Link

The method String.split() behaves differently in Java 7 (used by IdeOne) and Java 8 (probably used by some of the commenters and answerers). In the Java 8 JavaDoc documentation for String.split() , the following is written:

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.

So, according to Java 8, "google".split("") is equal to ["g","o","o","g","l","e"] .

This remark is not present in the Java 7 documentation, and indeed, in Java 7 it seems to be that "google".split("") is equal to ["", "g","o","o","g","l","e"] .

(Both in Java 7 and in Java 8 empty strings at the end of the array are removed.)

The best solution seems to be to just add code to ignore the first string if it is empty. (Note that the split("\\\\B") solution suggested in another answer yields unexpected results when your input consists of more than one word.)

Split your input according to non-word boundary.

string.split("\\B");

\\B matches between two non-word characters or two word characters.

DEMO

OR

split according to the below regex.

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

I have tried your code & there is no problem.

I think there may be a white space by mistake & that causes the problem.

use trim() to avoid such mistakes .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM