0

Say one has string input in the form below:

{ 'OTH', 'REJ', 'RSTO', 'RSTOS0', 'RSTR', 'S0', 'S1', 'S2', 'S3', 'SF', 'SH' }

What would be an efficient way to convert it to an array of Strings with each element being OTH, REJ, etc.?

I've currently done this using String.replace() and String.split() and have also considered the use of regex-s for the same, but was wondering whether there was a more easier/intuitive way of doing so.

1 Answer 1

2

Each of replace and split will need to iterate over your entire string which means you will need to iterate over it twice. With Scanner you can do it in one go, but you will need to use delimiter representing non-word characters (non A-Z a-z 0-9 _) which can be written in regex as \\W.

So your code can look like

String text = "{ 'OTH', 'REJ', 'RSTO', 'RSTOS0', 'RSTR', 'S0', 'S1', 'S2', 'S3', 'SF', 'SH' }";
List<String> tokens = new ArrayList<>();

Scanner sc = new Scanner(text);
sc.useDelimiter("\\W+");// one or more non-word character
while(sc.hasNext())
    tokens.add(sc.next());

System.out.println(tokens);//[OTH, REJ, RSTO, RSTOS0, RSTR, S0, S1, S2, S3, SF, SH]
sc.close();
Sign up to request clarification or add additional context in comments.

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.