Reputation: 73
I'm trying to first split a string into two values, and then split the second value in that string into more values. For some reason, the second value doesn't seem to splitting correctly.
I've tried a lot of refactoring and type checking, but it seems like the first part correctly returns a string, while the output is an array of strings, just not the strings I'm trying to return (single characters rather than the expressions separated by "|"
public class HelloWorld{
public static void main(String []args){
String starter = "Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15";
String [] newList = starter.split(":");
for(int i = 0; i < newList.length; i++) {
System.out.println(newList[i]);
}
String secondElement = newList[1];
String [] secondList = secondElement.split("|");
System.out.println(newList[1].getClass().getName());
System.out.println(secondList.getClass().getName());
for(int i = 0; i < secondList.length; i++) {
System.out.println(secondList[i]);
}
}
}
The result from the second for loop is just a list of individual characters, i.e. V, o, d, a, ... rather than Vodafone,STOCK,10 as the first element of the second list
Upvotes: 0
Views: 236
Reputation: 164139
You have to escape the '|'
character:
String [] secondList = secondElement.split("\\|");
because the argument of split()
is a Regex expression and |
is a special Regex character.
Upvotes: 4