wawanopoulos
wawanopoulos

Reputation: 9804

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;
}

Upvotes: 3

Views: 551

Answers (5)

Rachit
Rachit

Reputation: 3235

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.

Upvotes: 1

user1907906
user1907906

Reputation:

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.

Upvotes: 5

barak manos
barak manos

Reputation: 30146

Change:

sen.split(".");

To:

sen.split("\\.");

Upvotes: 2

assylias
assylias

Reputation: 328873

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("\\.");

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213391

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("\\.");

Upvotes: 3

Related Questions