Reputation: 163
I'm looking for a way to realise the following problem.
Starting from a String a I try to return a String[] equals
new String[]{Q},{ec.Qh},{ec.Q2}
Does anyone have any sugestions?
So far:
String a="Q={{ec.Qh}{ec.Q2}}";
int index_first = a.indexOf("=");
String name= a.substring(0,index_first);
String temp=a.substring(index_first+1, a.length());
temp=temp.replaceAll("\\{\\{","");
temp=temp.replaceAll("\\}\\{","\\,");
temp=temp.replaceAll("\\}\\}","");
String[] synonyms=temp.split(",");
//for(int i =0;i<synonyms.length;i++){System.out.println(synonyms[i]);}
String[] result=new String[]{name,synonyms} // does not work!
Upvotes: 0
Views: 144
Reputation: 272297
You could use a StringTokenizer thus:
new StringTokenizer(string, "{}")
Note that the StringTokenizer splits on the nominated characters (}
and {
) and doesn't return these. You should iterate through the tokenizer results using nextToken()
and add the results to a List<String>
.
It's useful here because of its simplicity but the documentation notes that StringTokenizer
is a legacy class, so you should use with discretion.
Upvotes: 3
Reputation: 533530
You can use
String s = "Q={{ec.Qh}{ec.Q2}}";
String[] parts = s.split("(=\\{\\{|}\\{|}})");
System.out.println(Arrays.toString(parts));
prints
[Q, ec.Qh, ec.Q2]
Upvotes: 2