简体   繁体   中英

Java string split gives array index out of bounds error

I came across this unusual error today. Can anyone explain me what I am doing wrong. Below is the code:

AreStringsPermuted checkStringPerObj = new AreStringsPermuted();
String[] inputStrings = {"siddu$isdud", "siddu$siddarth", "siddu$sidde"};
for(String inputString : inputStrings){
    String[] stringArray = inputString.split("$");
    if(checkStringPerObj.areStringsPermuted(stringArray[0],stringArray[1]))
            System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are permuted");
    else
            System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are not permuted");
        }

The above code errors out at when i try to split the string. For some reason split does not work when I try to divide each string using "$". Can any one explain me what I am doing wrong here?

Below is the error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at arraysAndStrings.TestClass.checkStringsPermuted(TestClass.java:24)
    at arraysAndStrings.TestClass.main(TestClass.java:43)

String.split() takes a regular expression , so you need to quote strings that contain characters that have special meanings in regular expressions.

String regularExpression = Pattern.quote("$");
for (String inputString : inputStrings) {
  String[] stringArray = inputString.split(regularExpression);

String.split( ) uses regex partern and $ has special meaning in regex(the end of line). In your case, use "\\$" instead of "$".

String []arrayString = inputString.split("\\$");

For more information, http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM