If you
String str = "a & b | (!c)";
get rid of spaces first:
String str2 = str.replaceAll(" ", "");
then get the array you want:
String[] array = str2.split("");
Update : based on a modified OP question, the following solution:
String str = "a_1 & b_2 | (!c_3)";
StringCharacterIterator sci = new StringCharacterIterator(str);
List<String> strings = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
for(char c = sci.first(); c != sci.DONE; c = sci.next()) {
if( c == ' ' ) {
continue;
}
else if(
c == '&' ||
c == '(' ||
c == ')' ||
c == '|' ||
c == '!')
{
if(sb.length() != 0) strings.add(sb.toString());
strings.add(String.valueOf(c));
sb = new StringBuilder();
}
else {
sb.append(c);
}
}
String[] finalArray = strings.toArray(new String[0]);
for (String string : finalArray) {
System.out.println(string);
}
source
share