1

I have a string of the following type:

{{a}{b}{c}{d}{e}{f}{g}{h}}

where a to h can be any string (which doesn't contain { and {).

What is the most efficient way of getting just a, b, c,..h in an Array maybe in Java?

Scanning through each character doesn't seem to be a good solution to me.

1
  • Have you tried split function() Commented Sep 22, 2015 at 11:47

3 Answers 3

2

Another option would be to use regular expressions, like so:

String text = "{{a}{b}{c}{d}{e}{f}{g}{h}}";

Pattern pattern = Pattern.compile("(?<=\\{)([^{}]*)(?=\\})");
Matcher matcher = pattern.matcher(text);

String[] result = new String[8];
for(int i = 0; i < result.length && matcher.find(); i++) {
    result[i] = matcher.group(1);
}
System.out.println(Arrays.toString(result));

The output was:

[a, b, c, d, e, f, g, h]

It is important to note that this solution, at least in its current form, will only find a maximum of 8 strings. If you need a more dynamic solution refer to Jordi Castilla's answer.

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

Comments

1

just use String::substring and String::split.

Be careful scaping } and { characters in split pattern.

String s = "{{a}{b}{c}{d}{e}{f}{g}{h}}";
s = s.substring(2, s.length()-2);
String[] ss = s.split("\\}\\{");
System.out.println(Arrays.toString(ss));

OUTPUT:

[a, b, c, d, e, f, g, h]

INPUT:

String s = "{{addaa}{grbwergb}{afñsljidhfWAc}{FFWEFWFd}{SGGRAERe}{ghetthsaf}{rweggwrgg}{wrgRGAEh}}";

OUTPUT:

[addaa, grbwergb, afñsljidhfWAc, FFWEFWFd, SGGRAERe, ghetthsaf, rweggwrgg, wrgRGAEh]

Comments

1

Try this

String originStr = "{{a}{b}{c}{d}{e}{f}{g}{h}}";
String tmpStr = originStr.replace("{{", "").replace("}}", "");
String[] resultArray = tmpStr.split("\\}\\{");

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.