HackerRank Java String Tokens problem solution YASH PAL, 31 July 2024 In this HackerRank java String Tokens problem in the java programming language you have 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. HackerRank Java String Tokens problem solution. import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.nextLine(); String[] tokens = S.split("[^a-zA-Z]"); int numTokens = 0; for (int i=0; i<tokens.length; ++i) if (tokens[i].length() > 0) numTokens++; System.out.println(numTokens); for (int i=0; i<tokens.length;++i) if (tokens[i].length() > 0) System.out.println(tokens[i]); } } Second solution import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner asdf = new Scanner(System.in); String a [] = asdf.nextLine().split("[ "!,?._'@". ]"); int size = a.length; for(int i = 0; i < a.length; i++){ if(a[i].compareTo("") == 0){ size = size - 1; } } System.out.println(size); for(int i = 0; i < a.length; i++){ if(a[i].compareTo("") != 0){ System.out.println(a[i]); } } } } A solution in java8 programming. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s = scan.nextLine(); s=s.replaceAll("[^a-z A-Z]"," "); s=s.replaceAll("\s+"," "); s=s.trim(); String [] arr=s.split(" "); if(s.length()>0){ System.out.println(arr.length); for (String i:arr) { System.out.println(i); } } else System.out.println(0); scan.close(); } } coding problems hackerrank solutions java
different objects, different parameters. tokens.length refers to the size of an array called tokens tokens.length() calls a method length() that provides the size of a String called tokens