StringIndexOutOfBoundException

后端 未结 2 374
攒了一身酷
攒了一身酷 2020-12-12 07:50

Hi I was just using stringbuilder to obtain certain part of the string using substring(int start, int end).. but I\'m having this error

08-17 20:27:40.737: E         


        
相关标签:
2条回答
  • 2020-12-12 08:46

    I just want to obtain the first 4 string of my phoneNumber string

    But your number has length lower than 4. If you want to get first four numbers you need to add simple condition:

    if (str.length() > 4) {
       // do your work
    }
    

    Don't forget that substring begins at the specified start and extends to the character at index end - 1.

    0 讨论(0)
  • 2020-12-12 08:47

    Are you using the substring() method but you no has length lower than 4 ,so if you want to get only four number use the following code.

    Ex:

       class  SubString
          {
    public static void main(String[] args) 
    {
    StringBuilder str = new StringBuilder(phoneNumber);
        if(str.length()>4){
        System.out.println(str.substring(0,4));
        }
         }
        }
    
    0 讨论(0)
提交回复
热议问题