-5

example:

String = "(a(b[}7cv)))"

the array should look like this: ["(","(","[","}",")",")",")"]

my try:

if(s.charAt(i) == "(" ){
    //add to array}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Zireal
  • 1
  • 1

2 Answers2

1

You can simply find them using regex and add them to a List

  public static void main(String[] args) {
    String foo = "(a(b[}7cv)))";
    List<String> allMatches = new ArrayList<String>();
    Matcher m = Pattern.compile("\\W")
        .matcher(foo);
    while (m.find()) {
      allMatches.add(m.group());
    }
    System.out.println(allMatches); 
  }

If it's only brackets you're after, you might want to take "[(){}\\]\\[]" as a regex for Pattern.compile

baao
  • 71,625
  • 17
  • 143
  • 203
0

How about getting non alphanumeric and add to the list

String s = "(a(b[}7cv)))";

    Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(s);
    var list = new ArrayList<String>();

    while (m.find()) {
        list.add(String.valueOf(s.charAt(m.start())));
    }
    System.out.println(Arrays.toString(list.toArray()));

Output

[(, (, [, }, ), ), )]
soorapadman
  • 4,451
  • 7
  • 35
  • 47