mercredi 2 octobre 2019

How do I account for whitespaces when counting words in a String?

I have written the below code to calculate the number of words for a given string. However, it does not account for whitespaces. How would I implement Character.isWhitespace(text.charAt(i)) in the below code to check for a double space? I am relatively new to Java.

String variable : text

character position: i

import java.util.Scanner;
public class Workbook {
public static void main(String[] args) {
    String w;
    int Count = 0;
    Scanner V1 = new Scanner(System.in);
    System.out.println("Enter word: ");
    w = V1.nextLine();
    for(int i = 0; i<w.length()-1; i++){
            if (w.charAt(i) == ' ' && w.charAt(i + 1) != ' ') {
                Count++;
            }

    }
    System.out.println("Number of words: " + (Count+1));
}

}

Example problem would be that if I have an example string "Hello nice to meet you !" would output 6 words - which is correct

but " Hello nice to meet you! " outputs 6 words instead of 5.

Aucun commentaire:

Enregistrer un commentaire