• Breaking News

    Friday, 30 October 2015

    SPLIT STRING BY DOT IN JAVA


    To split a string java provide split method of String class
    public String[] split(String regex)
    This method take regex as argument and split string based on that.
    Below is example of split which split string based on %.

    package com.kodemaker;
    
    public class SplitString {
         public static void main(String[] args) {
      
            String stringContainsDots = "kodemaker%com";
      
            String splitStringArray[] = stringContainsDots.split("%");
            for(String splitParts:splitStringArray){
              System.out.println(splitParts);
            }
        }
    }
    

    Output of above programme

    kodemaker
    com
    

    But if we want to split string based on Dot/Period then we have to escape that by \\

    package com.kodemaker;
    
    public class SplitStringContainsDotExample {
         public static void main(String[] args) {
      
         String stringContainsDots = "kodemaker.com";
      
             String splitStringArray[] = stringContainsDots.split("\\.");
             for(String splitParts:splitStringArray){
                System.out.println(splitParts);
             }
        }
    }
    

    Output of above programme

    kodemaker
    com
    

    No comments:

    Post a Comment