How to split a sentence into two parts

后端 未结 5 1315
半阙折子戏
半阙折子戏 2021-01-21 20:29

How to split a sentence into two parts in JAVA? If there is the following

String sentence = \"I love Java <=> I love Python\"

How can I

5条回答
  •  旧时难觅i
    2021-01-21 21:12

    It can be done using the method given below of class String

    METHOD: (public String[] split(String regex, int limit)
    
    • Regex: The String/Character you wish to remove & split remaining text
    • Limit: How many String that should be returned
    public class TestSplit
    
    {
    
        public static void main(String args[])
        {
            String str = new String("I Love Java <=> I Love Python");
            
        
            for (String retval: str.split("<=> ",2))
            {
                
                    System.out.println(retval);
            }
    
    
        }
    }
    

    Output:

    I Love Java

    I Love Python


    There are some other facts I am aware about are listed below

    • If you won't specify limit by 'keeping it blank'/'specify 0' then the compiler will split string every time '<=>' is found e.g.
    public class TestSplit
    
    {
    
        public static void main(String args[])
    
        {
    
            String str = new String("I Love Java <=> I Love Python <=> I Love Stackoverflow");
            for (String retval: str.split("<=> "))
            {
                    System.out.println(retval);
            }
    
    
        }
    }
    

    Output:

    I Love Java

    I Love Python

    I Love Stackoverflow

提交回复
热议问题