0

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("[#@]");?

2
  • 1
    "i need to split it an array of string removing # and @" — How should the final array look like? Commented Jul 29, 2014 at 20:15
  • 3
    You tagged this question as regex - any decent regex tutorial should quickly tell you the difference between "#@" and "[#@]". Commented Jul 29, 2014 at 20:17

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 @

Comments

1

[#@] means it will split on the # or the @.

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

Comments

1

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 #

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.