How to extract the first 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[] arr = s.split(" ", 2);

        System.out.println(arr[0]);
        System.out.println(arr[1]);
    }
}



/*
run:

java
c++ php python 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#";
        int i = s.indexOf(' ');
        
        String word = s.substring(0, i);
        
        System.out.println(word);
    }
}



/*
run:

java

*/

 



answered Jul 31, 2020 by avibootz
...