We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This is another way(most common way I have seen so far)
import java.util.Scanner;
public class TokenStringAnotherSolution{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//the purpose of using trim() is to remove trailing white spaces
/*Let's say we input "a ", then after splitting it, we can prevent from getting an unexpected array size of 2.*/
String s = scan.nextLine().trim();
scan.close();
//Use this regex to split
String[] arr = s.split("[_\\W\\s]+");
/*The purpose of this if-else statement is that to handle
* the leading white spaces. It doesn't remove the leading
* white spaces or makes the length of the array into 0,
*but get the job done. So, in this case, we are only handling
*the condition. */
//Starts here
if (arr.length==1) {
if (arr[0].isEmpty()) {
System.out.println(0);
}
//ends here
else {
System.out.println(arr.length);
System.out.println(arr[0]);
}
}
else {
System.out.println(arr.length);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
}
Cookie support is required to access HackerRank
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 →
This is another way(most common way I have seen so far)
import java.util.Scanner;
public class TokenStringAnotherSolution{ public static void main(String[] args) { Scanner scan = new Scanner(System.in);
}