input: he is a good, person.
desired output: {"he","is","a","good","person"}
program output: {"he","is","a","good"," ","person"}
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();
String[] ace = s.trim().split("[\\s+!,?._'@]");
scan.close();
System.out.println(ace.length);
for(String c : ace)
System.out.println(c);
}
}
am asking for first time here. need pointers for next time
You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.
split("\\s*,\\s*"); Here, trim() method removes leading and trailing spaces in the input string, and the regex itself handles the extra spaces around delimiter.
The split() method does not change the value of the original string. If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.
You could use RegExp:
String[] words = str.split("\\W+");
This is a Demo
You have a sequence of two delimiters between "good" and "person" - a space and a comma. You could tweak your regex to allow multiple consecutive delimiter characters as the same delimiter:
String[] ace = s.trim().split("[\\s+!,?._'@]+");
// Here ------------------------------------^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With