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

后端 未结 13 1938
小蘑菇
小蘑菇 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
    0 讨论(0)
  • 2020-11-29 03:07

    The simple one I used to do is

    str.contains(" ") ? str.split(" ")[0] : str
    

    Where str is your string or text bla bla :). So, if

    1. str is having empty value it returns as it is.
    2. str is having one word, it returns as it is.
    3. str is multiple words, it extract the first word and return.

    Hope this is helpful.

    0 讨论(0)
  • 2020-11-29 03:08

    You should be doing this

    String input = "hello world, this is a line of text";
    
    int i = input.indexOf(' ');
    String word = input.substring(0, i);
    String rest = input.substring(i);
    

    The above is the fastest way of doing this task.

    0 讨论(0)
  • 2020-11-29 03:09
    import org.apache.commons.lang3.StringUtils;
    
    ...
    StringUtils.substringBefore("Grigory Kislin", " ")
    
    0 讨论(0)
  • 2020-11-29 03:12

    To simplify the above:

    text.substring(0, text.indexOf(' ')); 
    

    Here is a ready function:

    private String getFirstWord(String text) {
    
      int index = text.indexOf(' ');
    
      if (index > -1) { // Check if there is more than one word.
    
        return text.substring(0, index).trim(); // Extract first word.
    
      } else {
    
        return text; // Text is the first word itself.
      }
    }
    
    0 讨论(0)
  • 2020-11-29 03:13

    like this:

    final String str = "This is a long sentence";
    final String[] arr = str.split(" ", 2);
    System.out.println(Arrays.toString(arr));
    

    arr[0] is the first word, arr[1] is the rest

    0 讨论(0)
提交回复
热议问题