Sometimes you want to split a String but still need the token for finding the parts you need. I setup an example to deal with this:
You have a String that contains a list of friends. All you want is to print out those names and not the first part of the String.
private void checkNames(){
String name = "This is a list with friends, Fred, Ted, Robert,Maria, Roberta, Kaya";
String splitExp = "(?=[:,])"; //The last char in the brackets [] is the token in our case the comma.
String[] splittedNames = name.split(splitExp);
for (int i = 0; i < splittedNames.length; i++) {
if(splittedNames[i].startsWith(",")){
//print it remove the comma and spaces
System.out.println(splittedNames[i].substring(1).trim());
}
}
This will give you a clean list of your friends names.
Have fun.
Geen opmerkingen:
Een reactie posten