Separating a string in java
Hello,
I need to cut a string into several pieces but retaining the separator in pieces.
example:
my chain "or (varname) is a (Subject)
Expected Result: [ "be", "(varname)", "being one", "(Subject)]
separators are the brackets ().
I tried several solutions (split, StringTokenizer ...) but I can only have [ "be", "varname", "being one", "Subject"]
Someone would have an idea? Thanks in advance.
Re: Separating a string in java
Hello,
Just be your own separation method using indexOf indexOf ('{') and ('}'). You search the '(', if you think you are looking for the ')' nearest you make a substring and do it again for the rest of the chain. I think this should take long time to code such a program , it is quit simple. If you need help about the class and the methods provided by the java you can find then on the official site of the sun.
Re: Separating a string in java
Hello,
You can use regular expressions, but if I do not control enough to find the solution. I will still file the snippet I just tested:
Code:
String s = "This is (variable) (I) variable2 sing";
List l = findVars(chain);
System.out.System.out.println(l);
Here is the code
Code:
@ SuppressWarnings("unchecked")
Public static List findVars(String input) {
Pattern p = Pattern.compiles("\\{.*\\}");
Matcher m = p.matcher(input);
List list = new ArrayList();
if (m.find()) {
do {
list.add(m.group());
} while (m.find());
return list;
}
return null;
}
Re: Separating a string in java
Hello,
This is not the solution to the problem in question, but just for info, the "*" RegExp is the default "greedy" (greedy), i.e that "{.*} in a string like "(variable) is my () variable2" will matcher whole chain, including the first ')' encountered. One can remedy this by adding "?" after the *, which gives {.*?} which allow to stop the very first ")" found.
Re: Separating a string in java
Hello,
Here is the code that can help you, just go through it
Code:
private List <String> spwtdel(String str, String OPENLiMiT, String closeLimit)
{
List lt = <String> new ArrayList <String>();
int froplm = str.indexOf(OPENLiMiT);
int frcllm = str.indexOf(closeLimit, froplm);
while ((froplm! = -1) && (frcllm! = -1))
{
if (froplm> 0)
lt.add(str.substring(0, FirstOpenLimit));
lt.add(str.substring(froplm, frcllm + 1));
if (frcllm <str.length())
str = str.substring(frcllm + 1, Str.length());
else
str = "";
froplm = str.indexOf(OPENLiMiT);
frcllm = str.indexOf(closeLimit, froplm);
}
if (str.length() > 0)
lt.add(str);
return lt;
}
Re: Separating a string in java
Hello,
Here is another program that will interest you. Have a look at it
Code:
List <String> split(String string) {
ArrayList str = <String> new ArrayList <String>();
Pattern pat = Pattern.compiles("\\{(.*?)\\}");
Matcher mat = pat.mat(string);
int ls = 0;
while (mat.find()) {
str.add(string.substring(ls, match.home()));
str.add(mat.group());
ls = mat.end();
}
if (ls! = string.length())
str.add(string.substring(ls, string.length()));
return str;
}