Regarding the subscript out-of-bounds exception when using split to separate characters

Regarding the subscript out-of-bounds exception when using split to separate characters

error code

String fileName="test.txt";
String[] splitResult=fileName.split(".");
String suffix=splitResult[1];

** Output result: **

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

solution

Add "\" to the split character to become an escape character

  String fileName="test.txt";
  String[] suffix=fileName.split("\\.");
  System.out.println(suffix[1]);

** Output result: **

txt

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/106741806