Tuesday, June 13, 2017

[Solved] String split does not pick up the trailing /ending empty string

For example, you have a string:
      String str = "You are,indeed,very,very beautiful!, ......,,,,";

Then you use the split method to get all the tokens.

      String [] tokens = str.split(",");

You expect this: {"You are", "indeed", "very",  "very beautiful!", " ......", "", "," "", ""}
But you get this: {"You are", "indeed", "very",  "very beautiful!, " ......"}

The String split("<delimiter>") method, removes the trailing empty strings from the result by default. To include these empty trailing strings in the result array, you need to use its overloaded form, split("<delimiter>", <a negative integer>) or split("<delimiter>", Integer.MAX_VALUE).

      String[] tokens = str.split(",", -1);

will give you the array you expect.

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment