Search code examples
javastringindexoutofbounds

Java StringIndexOutOfBoundsException encountered when reading substring


So I have this java class which reads a file with multiple lines and whenever it reaches this part

      F    C    Y

It's supposed to read the values of that (return F, C, Y)

I've tried ClassString = temp.substring(0, 20).trim();

but it always returns StringIndexOutOfBoundsException (eString index out of range: 20)

Not sure why, I counted that line from the start and Y is in index 20.


Solution

  • Here is how I would do it, of course some error checking might be needed.

    temp = temp.trim();
    String[] result = new String[] {String.valueOf(temp.charAt(0)),
                                    temp.substring(1, temp.length()-2).trim(), 
                                    String.valueOf(temp.charAt(temp.length()-1))};
    

    or as a char array

    temp = temp.trim();
    char[] result2 = new char[] {temp.charAt(0),
                                 temp.substring(1, temp.length()-2).trim().charAt(0), 
                                 temp.charAt(temp.length()-1)};