0

I'm struggling other than brute force method to split

String str = "a{b}c{d}" 

into

String[] arr;
arr[0] = "a"
arr[1] = "{b}"
arr[2] = "c"
arr[3] = "{d}"

Wondering if there's a more efficient way other out there than using indexOf and subString

Radiodef
  • 37,180
  • 14
  • 90
  • 125
slee
  • 344
  • 3
  • 5
  • 15

5 Answers5

4

Based on your current edit it looks like you want to split on place which is either

  • directly before {
  • directly after }

In that case you can use split method which supports regex (regular expression). Regex provides lookaround mechanisms like

  • (?=subregex) to see if we are directly before something which can be matched by subregex
  • (?<=subregex) to see if we are directly after something which can be matched by subregex

Also { and } are considered regex metacharacters (we can use them like {m,n} to describe amount of repetitions like a{1,3} can match a, aa, aaa but not aaaa or more) so to make it normal literal we need to escape it like \{ and \}

Last thing you need is OR operator which is represented as |.

So your code can look like:

String str = "a{b}c{d}";
String[] arr = str.split("(?=\\{)|(?<=\\})"); // split at places before "{" OR after "}"
for (String s : arr){
    System.out.println(s);
}

Output:

a
{b}
c
{d}

Demo: https://ideone.com/FdUbKs

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

just use the String.split() method (documentation)

arr = str.split()
Sam
  • 1,542
  • 2
  • 13
  • 27
1

You may use the String.split(String delimiter) method :

String str = "a {b} c {d}";
String[] arr = str.split(" ");
System.out.println(Arrays.toString(arr));  //  [a, {b], c, {d}]
azro
  • 53,056
  • 7
  • 34
  • 70
1

Use String.split()...

String[] arr = str.split(" ");

haba713
  • 2,465
  • 1
  • 24
  • 45
1

I don't know if it's as efficient as the previous regex solutions; I'm putting a single white space before { and after } then splitting string by " ":

    String str = "a{b}c{d}";
    String[] split = str.replace("{"," {").replace("}","} ").split(" ");
    System.out.println(Arrays.toString(split));

Desired output:

    [a, {b}, c, {d}]
AntiqTech
  • 717
  • 1
  • 6
  • 10