[英]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.split()
采用正则表达式 ,因此您需要引用包含在正则表达式中具有特殊含义的字符的字符串。
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). String.split()使用正则表达式partern,而$在正则表达式(行尾)中具有特殊含义。 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 有关更多信息,请访问http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.