Reputation: 2742
While solving a UVa question, I got this String
and I need to split it an array of String
removing #
and @
Brazil#2@1#Scotland
I was getting a ArrayOutOfBounds
exception when I used,
matchSummary.split("#@");
after researching solutions for this UVa question, I found that other experienced competitive programmers have done it like this,
string.split("[#@]");
and this passes the verdict of online judge.
I cant get this String
split for this aforementioned String
My complete solution for this question is available here- see
Can anybody explain to me why my code worked with split("[#@]");
?
Upvotes: 0
Views: 233
Reputation: 48404
In Java regular expressions, characters enclosed in square brackets []
are called a character class.
This...
String input = "Brazil#2@1#Scotland";
System.out.println(Arrays.toString(input.split("[#@]")));
... will split the String
with either delimiter #
or @
, regardless of the order, and output:
[Brazil, 2, 1, Scotland]
It is equivalent in this case to:
System.out.println(Arrays.toString(input.split("#|@")));
However, splitting with #@
not enclosed by []
would search for a sequence of #
followed by @
.
This would not trigger any ArrayIndexOutOfBoundsException
per se, it would just return a 1-sized array
containing the original input String
.
However, you're probably assuming the array
size as > 1
later in the code, hence the Exception
.
Upvotes: 2
Reputation: 127
The reason why the split function is giving you an error is because @ and # are not together in the string, i would suggest using the StringTokenizer to split the string.
so create a new instance of it - StringTokenizer s = new StringTokenizer("Brazil#2@1#Scotland");
then set the delimeter to @ then split them, and then split them with the delimeter #
Upvotes: 1
Reputation: 9331
Basically using:
split("#@");
Will try to split only if it matches the characters #
@
concurrently
by using:
split("[#@]");
You are selecting from the class to either split on #
or @
Upvotes: 2
Reputation: 565
[#@]
means it will split on the #
or the @
.
For more information: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Upvotes: 1