Reputation: 13
I have a string with an unknown length that looks like this
a ,b, c: integer; d,e :real;
How could I split this at the commas without getting the words and characters that follow the last commas of the variables? Or is there a way to split the variables at the commas after it is in an array from splitting at the colon? The closest I have come is with this method
// the variablesArray would contain a ,b, c in the first index
// and d,e in the second index.
public static String[] variables(String[]variablesArray) {
String variables[] = new String[variablesArray.length];
for(int i = 0; i < variablesArray.length; i++){
String temporary = variablesArray[i];
String arr[] = temporary.split(",");
}
return variables;
}
When I run this it only returns the first character in the array index
//prints [a d]
Upvotes: 1
Views: 124
Reputation: 2664
is this what you want?
String[] result = s.replaceAll("\\w{2,}", "").replaceAll("[:;,]"," ").replaceAll("\\u0020+"," ").split(" ");
Array result
now holds only the single chars. Testing with:
for(String c: array)
System.out.println(c);
will output:
a
b
c
d
e
Upvotes: 0
Reputation: 17
I think you have a problem. temporary.split(",");
is an array then you have appened it to be as a part of another array. Thats troublesome .... I mean:
Array
0 => Array
0 => a
1 => b
So you should use:
String arr = temporary.split(",");
Upvotes: 0
Reputation: 96
if myString
is equal to "a ,b, c: integer; d,e :real;"
the following with output a b c d e
for (String type : myString.split(";")) {
String sub = type.substring(0, type.indexOf(":"));
for (String name : sub.split(",")) {
System.out.println(name);
}
}
Upvotes: 1
Reputation: 25409
You'll need to break the problem up:
;
.:
Note that this will give you the array {"a ,b, c", "d,e"}
as I understand from your question that you want it. If you want to split that further, you'll need to split each of these strings again, this time at ,
. Note that you'll need to change the type of your array from String[]
to String[][]
in this case. You'll get {{"a", "b", "c"}, {"d", "e"}}
.
If you also want to strip whitespace during the process of splitting, add \s*
before and after the split character. For example: "a, b,c , d".split("\\s*,\\s*")
returns {"a", "b", "c", "d"}
.
Upvotes: 1
Reputation: 4262
how about following?
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
String str = "a ,b,c: integer;d,e :real;";
String[] stra = str.split(";");
for(String st: stra){
//System.out.println(st);
String[] stra2 = st.split(",");
for(String s: stra2){
System.out.println(s);
list.add(String.valueOf(s.charAt(0)));
}
}
System.out.println(list);
}
OP
a
b
c: integer
d
e :real
[a, b, c, d, e]
Upvotes: 0