How to remove all words of a string except the first and last word in Java

1 Answer

0 votes
public class MyClass {
 
    public static void main(String[] args) {
        String str = "Java is a high-level, class-based, object-oriented programming language";
        
        int firstSpaceIndex = str.indexOf(" ");
        int lastSpaceIndex = str.lastIndexOf(" ");
        
        str = str.substring(0, firstSpaceIndex) + str.substring(lastSpaceIndex);

        System.out.println(str); 
    }
}
 


 
/*
         
run:
   
Java language
     
*/
 

 



answered Oct 9, 2023 by avibootz

Related questions

...