Wednesday, April 28, 2010

string methods

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

No comments:

Post a Comment