You are viewing a single comment's thread. Return to all 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();
} }
Seems like cookies are disabled on this browser, please enable them to open this website
Java String Tokens
You are viewing a single comment's thread. Return to all comments →
import java.util.*;
public class Solution {
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();
} }