Sunday 3 April 2011

How to Split a String in java Exmple explained

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

No comments:

Post a Comment