Need to split a string into two parts in java

后端 未结 2 884
无人及你
无人及你 2020-12-11 18:01

I have a string which contains a contiguous chunk of digits and then a contiguous chunk of characters. I need to split them into two parts (one integer part, and one string)

2条回答
  •  长情又很酷
    2020-12-11 19:07

    There's always an old-fashioned way:

    private String[] split(String in) {    
      int indexOfFirstChar = 0;
      for (char c : in.toCharArray()) {
        if (Character.isDigit(c)) {
          indexOfFirstChar++;
        } else {
          break;
        } 
      }    
      return new String[]{in.substring(0,indexOfFirstChar), in.substring(indexOfFirstChar)};
    }
    

    (hope it works with digit-only or char-only Strings too - can't test it here - if not, take it as a general idea)

提交回复
热议问题