Remove first word from a string in Java

前端 未结 9 1982
天涯浪人
天涯浪人 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: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));
    

提交回复
热议问题