3

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

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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

Comments

2

Change:

sen.split(".");

To:

sen.split("\\.");

Comments

1

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.

1 Comment

It wouldn't compile, you've to use `\` as others have used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.