Java String Tokens

  • + 0 comments

    import java.util.*;

    public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
    

    String s = scan.nextLine(); // s = s.trim();

    // Split by commas, question marks, spaces, and apostrophes String[] s1 = s.split("[^a-zA-Z0-9]+");

    int nonEmptyCount = 0; for (String word : s1) { if (!word.isEmpty()) { nonEmptyCount++; } }

    // Print the word count first System.out.println(nonEmptyCount);

    // Print each non-empty word for (String word : s1) { if (!word.isEmpty()) { System.out.println(word); } }

    This Worked for me. scan.close();

    } }