05.0 Java Notes‎ > ‎Java: String‎ > ‎

Java String: substring()

Extracts a part of a string




    public void subStringExample1()
    {
        String phrase, firstWord;
        int positionOfSpace;

        phrase = "find the first word in this sentence";
        // find the first space
        positionOfSpace = phrase.indexOf(" ");
       
        // assume that the first word end before the first space in the sentence
        firstWord = phrase.substring(0,positionOfSpace);
        
        // output the results
        System.out.println(phrase);
        System.out.println(firstWord);

    }
    

    public void subStringExample2()
    {
        String phrase;
        int positionOfSpace;

        phrase = "remove the first word in this sentence";
        // find the first space
        positionOfSpace = phrase.indexOf(" ");
        // show the phrase before changes
        System.out.println(phrase);
        // remove the first word from the phrase
        phrase = phrase.substring(positionOfSpace, phrase.length());
        
        // output the results
        System.out.println(phrase);
      }    

Comments