-1

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
husnul
  • 130
  • 3
  • 11

1 Answers1

1

= 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]+

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • Yeah, I know that. But can you give me suggestion what delimiter should I use. – husnul Dec 16 '12 at 07:59
  • May be you can use the same logic as above and and remove the empty value from the array like mentioned [here](http://stackoverflow.com/questions/4150233/remove-null-value-from-string-array-in-java) – Jayamohan Dec 16 '12 at 09:06