Over 500 Magazines for FREE!

Yes! You can subscribe to ALL of them. They will be shipped to your home FREE of cost!
Kindly click here to apply!

Java String Split Example

  1. /*
  2. Java String split example.
  3. This Java String split example describes how Java String is split into multiple
  4. Java String objects.
  5. */
  6.  
  7. public class JavaStringSplitExample{
  8.  
  9. public static void main(String args[]){
  10. /*
  11.   Java String class defines following methods to split Java String object.
  12.   String[] split( String regularExpression )
  13.   Splits the string according to given regular expression.
  14.   String[] split( String reularExpression, int limit )
  15.   Splits the string according to given regular expression. The number of resultant
  16.   substrings by splitting the string is controlled by limit argument.
  17.   */
  18.  
  19. /* String to split. */
  20. String str = "one-two-three";
  21. String[] temp;
  22.  
  23. /* delimiter */
  24. String delimiter = "-";
  25. /* given string will be split by the argument delimiter provided. */
  26. temp = str.split(delimiter);
  27. /* print substrings */
  28. for(int i =0; i < temp.length ; i++)
  29. System.out.println(temp[i]);
  30.  
  31. /*
  32.   IMPORTANT : Some special characters need to be escaped while providing them as
  33.   delimiters like "." and "|".
  34.   */
  35.  
  36. System.out.println("");
  37. str = "one.two.three";
  38. delimiter = "\\.";
  39. temp = str.split(delimiter);
  40. for(int i =0; i < temp.length ; i++)
  41. System.out.println(temp[i]);
  42.  
  43. /*
  44.   Using second argument in the String.split() method, we can control the maximum
  45.   number of substrings generated by splitting a string.
  46.   */
  47.  
  48. System.out.println("");
  49. temp = str.split(delimiter,2);
  50. for(int i =0; i < temp.length ; i++)
  51. System.out.println(temp[i]);
  52.  
  53. }
  54.  
  55. }
  56.  
  57. /*
  58. OUTPUT of the above given Java String split Example would be :
  59. one
  60. two
  61. three
  62. one
  63. two
  64. three
  65. one
  66. two.three
  67. */

escape

the carrot symbol(^) must be escaped as well.

Post new comment

To combat spam, please enter the code in the image.




Do you have a better example?
We're sure you have hundreds of Java program examples.

Spare some time and submit your java example here even if you think it's too small to contribute.

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!