I want to split a given string according to the given format -> ,;:.?!
.What I am doing is given below, but whenever it is encountering more than 1 space it is adding space to the array. I just want the word not the space.
INPUT::
hello Hello HEllo hi hi: hi! Welcome, welcome
OUTPUT::
13
hello
Hello
HEllo
hi
hi
hi
Welcome
welcome
EXPECTED OUTPUT::
8
hello
Hello
HEllo
hi
hi
hi
Welcome
welcome
import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String[] arr = s.split("[ ,;:.?!]"); System.out.println(arr.length); for (String string : arr) { System.out.println(string); } } }
Advertisement
Answer
Your regexp matching only 1 character, you can add {1,2}
to it so it would match 1 or 2 characters, or you can even replace it with +
to match 1 or more.
import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String[] arr = s.split("[ ,;:.?!]{1,2}"); System.out.println(arr.length); for (String string : arr) { System.out.println(string); } } }