How to extract the last word from a string in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "java c++ php python c#";

        String word = s.substring(s.lastIndexOf(" ") + 1);
        
        System.out.println(word);
    }
}



/*
run:

c#

*/

 



answered Jul 31, 2020 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "java c++ php python c#";

        String[] arr = s.split(" ");
        
        String word = arr[arr.length - 1];
        
        System.out.println(word);
    }
}



/*
run:

c#

*/

 



answered Jul 31, 2020 by avibootz
...