Java String Tokens

  • + 1 comment

    if the input string consists of only white spaces

    the s.split(" ") will give 0

    it produces unwanted result if there are leading or trainling

    white spaces so you will need to use s.trim() method before

    performing any string operation

    Try following code.

    public class TestWhiteSpace{
      public static void main(String []args){
        String test_str = "   a    b   ";
        String[] test   = test.split("[ ]+");
        System.out.println(test.length());
        int count = 0;
        for (String str : test) {
          count++;
          Syste.out.println(str + ": " + count);
        }
      }
    }