Delete everything after part of a string

后端 未结 10 2167
时光取名叫无心
时光取名叫无心 2020-12-03 09:25

I have a string that is built out of three parts. The word I want the string to be (changes), a seperating part (doesn\'t change) and the last part which changes. I want to

10条回答
  •  暖寄归人
    2020-12-03 10:11

    Clean way to safely remove until a string, and keep the searched part if token may or may not exist.

    String input = "Stack Overflow - A place to ask stuff";
    String token = " - ";
    String result = input.contains(token)
      ? token + StringUtils.substringBefore(string, token)
      : input;
    // Returns "Stack Overflow - "
    

    Apache StringUtils functions are null-, empty-, and no match- safe

提交回复
热议问题