How to get 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 c++ python c#";

        String firstWord = s.substring(0, s.indexOf(' '));

        System.out.println(firstWord);
    }
}
  
  
  
/*
run:
  
java

*/

 



answered Oct 30, 2020 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "java c c++ python c#";
        String [] arr = s.split("\\s+"); 

        String first_word = arr[0];

        System.out.println(first_word);
    }
}




/*
run:

java

*/

 



answered Feb 8, 2022 by avibootz

Related questions

1 answer 169 views
2 answers 158 views
1 answer 128 views
1 answer 162 views
2 answers 199 views
3 answers 292 views
...