简体   繁体   中英

Split function doesn't work

Here is a function which take a long String and return a string divided in paragraph.

The problem is that k is empty. Why split() function doesn't work?

private String ConvertSentenceToParaGraph(String sen) {
    String nS = "";
    String k[] = sen.split(".");

    for (int i = 0; i < k.length - 1; i++) {
        nS = nS + k[i] + ".";
        Double ran = Math.floor((Math.random() * 2) + 4);

        if (i > 0 && i % ran == 0) {
            nS = nS + "\n\n";
        }
    }
    return nS;
}

String.split(String regex) takes a regular expression. A dot . means 'every character'. You must escape it \\\\. if you want to split on the dot character.

split expects a regular expression, and "." is a regular expression for "any character". If you want to split on each . character, you need to escape it:

String k[] = sen.split("\\.");

split() method takes a regex. And . is a meta-character, which matches any character except newline. You need to escape it. Use:

String k[] = sen.split("\\.");

Change:

sen.split(".");

To:

sen.split("\\.");

You need to escape the dot, if you want to split on a dot:

String k[] = sen.split("\\.");

A . splits on the regex . , which means any character.

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