How to count the number of words per line?

I need to count the number of words, and I guess the right way to do this is by calculating the number of times that the previous character in the string is not a letter (i.e. other characters), because this should assume that there will be colons, spaces, tabs and others in the string signs. So my first idea was to scroll through each character and count how many times you did not get the letter of the alphabet

    for(int i = 0; i < string.length(); i++) {
      for(int j = 0; i < alphabets.length(); j++) {
       if (string.charAt(i-1) == alphabets.charAt(j)) {
           counter++;
       }
     }
   }

However, because of this, I always get an array from outside. So, I need a little help or another way that can really be more effective. I was thinking of using Matches only for [a-zA-z], but I'm not sure how to handle the char to be comparable to the string when counting how many times this happens.

thank

+5
7

"[A-Za-z]" . split , :

String [] words = " : , , ".split( "[^ A-Za-z] +" );

: , .

public static int countWords(String str) {
    char[] sentence = str.toCharArray();
    boolean inWord = false;
    int wordCt = 0;
    for (char c : sentence) {
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
            if (!inWord) {
                wordCt++;
                inWord = true;
            }
        } else {
            inWord = false;
        }
    }
    return wordCt;
}
+2

String.split() . :

int words = myString.split("\s+").length;
+3

, .

  • , ?
  • , ( )?

, - . , .

  • , .
  • - , .
  • -, , , .
+2

, IndexOutOfBoundsException, , , 0, string.charAt(i-1), , 0-1 -1. , , .

+1

= 0 i,

string.charAt(i-1) = string.charAt(-1),

- .

:

for (int j = 0; i <alphabets.length (); j ++) {

You can also consider apostrophes as parts of words.

+1
source
   if (string.charAt(i-1) == alphabets.charAt(j)) {
       counter++;
   }

You increment the counter if the character has some alphabet character. You must increase it if it is not a symbol of the alphabet.

0
source

Use exactly the same

String s = "I am Juyel Rana, from Bangladesh";
int count = s.split(" ").length;
0
source

All Articles