Remove first word from a string in Java

前端 未结 9 1888
天涯浪人
天涯浪人 2020-12-29 12:20

What\'s the best way to remove the first word from a string in Java?

If I have

String originalString = \"This is a string\";

I want to r

相关标签:
9条回答
  • 2020-12-29 12:47

    You can use substring

    removedWord = originalString.substring(0,originalString.indexOf(' '));
    originalString = originalString.substring(originalString.indexOf(' ')+1);
    
    0 讨论(0)
  • 2020-12-29 12:50

    You can check where is the first space character and seperate string.

    String full = "Sample Text";
    String cut;
    int pointToCut = full.indexOf( ' ');
    
    if ( offset > -1)
    {
      cut = full.substring( space + 1);
    }
    
    0 讨论(0)
  • 2020-12-29 12:53

    Simple.

     String o = "This is a string";
     System.out.println(Arrays.toString(o.split(" ", 2)));
    

    Output :

    [This, is a string]
    

    EDIT:


    In line 2 below the values are stored in the arr array. Access them like normal arrays.

     String o = "This is a string";
     String [] arr = o.split(" ", 2);
    
     arr[0] // This
     arr[1] // is a string
    
    0 讨论(0)
  • 2020-12-29 12:57

    For an immediate answer you can use this :

    removeWord = originalString.substring(0,originalString.indexOf(' '));
    originalString = originalString.substring(originalString.indexOf(' '));
    
    0 讨论(0)
  • 2020-12-29 12:57

    Try this using an index var, I think it's quite efficient :

    int spaceIdx = originalString.indexOf(" ");
    String removedWord = originalString.substring(0,spaceIdx);
    originalString = originalString.substring(spaceIdx);
    

    Prior to JDK 1.7 using below method might be more efficient, especially if you are using long string (see this article).

    originalString = new String(originalString.substring(spaceIdx));
    
    0 讨论(0)
  • 2020-12-29 12:59

    You can use the StringTokenizer class.

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