I want to split this String to words
“public static 9 Scanner input = new Scanner(System.in);”
the problem is when I run my program the word after input is ” ” or space, next word is new. It seems like this :
Kata 1 = public Kata 2 = static Kata 3 = 9 Kata 4 = Scanner Kata 5 = input Kata 6 = Kata 7 = new Kata 8 = Scanner Kata 9 = System
What I want is after “input” is directly to “new”. Here is my code :
int index=0;
String kata [] = kalimat.split("\\s+|\\W+");
System.out.println("\nKata dalam kalimat : ");
for (String s:kata){
System.out.println("Kata "+(index+1)+" = "+s);
index++;
}
System.out.println("Jumlah kata : " + kata.length);
I know that the problem is delimiter that I used for .split()
I want the output will be :
Kata 1 = public Kata 2 = static Kata 3 = 9 Kata 4 = Scanner Kata 5 = input Kata 6 = new Kata 7 = Scanner Kata 8 = System
=is not a “word character” ([a-zA-Z_0-9]), so\\W+sees it as “not a word” and ignores it.See: http://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
Edit to add: So the answer is … use a set and add it.
[=\\s\\W]+