HackerRank Java- String Tokens




Given a string, s, matching the regular expression [A-Za-z !,?._'@]+, split the string into tokens. We define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.



  1. import java.io.*;
  2. import java.util.*;
  3. public class Solution {
  4. public static void main(String[] args) {
  5. Scanner scan = new Scanner(System.in);
  6. String s = scan.nextLine();
  7. scan.close();
  8. s = removeLeadingNonLetters(s);
  9. /* Check special cases */
  10. if (s.length() == 0) {
  11. System.out.println(0);
  12. return;
  13. }
  14. /* Split on all non-alphabetic characters */
  15. String[] words = s.split("[^a-zA-Z]+");
  16. /* Print output */
  17. System.out.println(words.length);
  18. for (String word : words) {
  19. System.out.println(word);
  20. }
  21. }
  22. private static String removeLeadingNonLetters(String str) {
  23. int i;
  24. for (i = 0; i < str.length(); i++) {
  25. if (Character.isLetter(str.charAt(i))) {
  26. break;
  27. }
  28. }
  29. return str.substring(i);
  30. }
  31. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube