What is the best way to extract the first word from a string in Java?

后端 未结 13 2103
小蘑菇
小蘑菇 2020-11-29 02:38

Trying to write a short method so that I can parse a string and extract the first word. I have been looking for the best way to do this.

I assume I would use s

13条回答
  •  再見小時候
    2020-11-29 03:02

    You can use String.split with a limit of 2.

        String s = "Hello World, I'm the rest.";
        String[] result = s.split(" ", 2);
        String first = result[0];
        String rest = result[1];
        System.out.println("First: " + first);
        System.out.println("Rest: " + rest);
    
        // prints =>
        // First: Hello
        // Rest: World, I'm the rest.
    
    • API docs for: split

提交回复
热议问题