Split function does not work

Here is a function that takes a long string and returns a string split in a paragraph.

The problem is that k is empty. Why split()does the function not 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;
}
+3
source share
5 answers

String.split(String regex)accepts regular expression. The dot .means "every character." You must avoid this \\.if you want to break the dots into a character.

+5
source

splitexpects a regular expression, and "."a regular expression for "any character". If you want to divide by each character ., you need to avoid it:

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

split() . . , , . . :

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

:

sen.split(".");

To:

sen.split("\\.");
+2
source

You need to avoid a dot if you want to split into a dot:

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

A is .broken up into a regular expression ., which means any character.

+1
source

All Articles