带字数的Android字符串制动器

时间:2015-06-27 22:17:13

标签: android string count

我想计算字符串中的字符数,如果计数器达到限制则会换行。但我不知道如何解决。

我发现了单词计数器,但是如何在特定位置添加一个中断?例如在每个第四个单词之后。

public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

0 个答案:

没有答案