1

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)

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Wow. Thanks, forgot that split looks for pattern as opposed to characters.
@Siddarth You're welcome. If my answer solves your problem, please accept the answer.
Stack overflow does not allow me to accept right away. Will accept in some time, you were too quick ;)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.