String Tokens program with Java HackerRank Solutions
Objective
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.
Input Format
A single string, s.
Constaints
- 1<=length of s<=4.10^5.
- s is composed of any of the following: English alphabetic letters, blank spaces, exclamation points (
!
), commas (,
), question marks (?
), periods (.
), underscores (_
), apostrophes ('
), and at symbols (@
).
Output Format
On the first line, print an integer, n, denoting the number of tokens in string s (they do not need to be unique). Next, print each of the n tokens on a new line in the same order as they appear in input string s
Sample Input
He is a very very good boy, isn't he?
.Sample Output
10
He
is
a
very
very
good
boy
isn
t
he
Solution
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().trim();
scan.close();
String[] tokens=s.split("[ !,?._'@]+");
System.out.println(tokens.length);
for(String token:tokens)
{
System.out.println(token);
}
}
}
Steps involved in this Solution:
1. Import the necessary package for the Scanner class to read input from the user.
2. Define a class (e.g., Solution) to encapsulate the program's functionality.
3. Create a main method, the entry point of the Java program.
4. Utilize a Scanner object to read a line of input from the user, representing the original string
5. Use the split method of the String class to split the input string into an array of tokens based on specified delimiters, like spaces and specified characters.
6. Print the total number of tokens obtained after the string tokenization.
7. Iterate through the array of tokens and print each token on a new line.