0

I have a string which is like

"AB-123,XYZ-456,AB-11,AB-3423,XYZ-1" 

I want to separate out all AB's in one string and XYZ in another. I can do it using stringtokenizer and match the AB's and XYZ and build tow new strings out of it, is there a better way to achieve this.

Thanks.

2
  • 2
    a better way in what sense? Is your current way not working, inefficient, hard to read, etc.? Commented Dec 6, 2011 at 20:00
  • sure its working, i am thinking if there is a better way that i do not may be split the strings based on some reg-ex i do not even know if that is possible. Commented Dec 6, 2011 at 20:08

1 Answer 1

3

I would personally split the two tasks:

  • Split the single string into a list / array / whatever
  • Go through the results and add the strings to one result list or the other

These are logically independent steps, and I think your code will be clearer if you treat them separately. You should also consider what you want to happen if one of the parts doesn't start with either AB or XYZ.

For the splitting part, you could either use String.split or Guava's Splitter class.

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

2 Comments

String.split and Guava'splitter,which is better?I mean easier to use with more beautiful code style?
@chance: Well if you're going to split in the same way in multiple places, I'd definitely use Splitter. For a one off, String.split is okay...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.