Example of what I want to do:
If you pass in "abc|xyz" as the first argument and "|" as the second argument the method returns List("abc","xyz")
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
//stores each character from string in newString.
newString += string.charAt(i);
}
newString.replace(delimiter, "");
//remove string from arraylist 'list'.
list.remove(string);
//add newString to arraylist 'list'.
list.add(newString);
return list;
}
Try using the split method:
return Arrays.asList(string.split("\\|"));
The two backslashes are there because split accepts a regex, and | is a special character in regexes. Also, backslash is a special character in Java strings. So the first backslash escapes the second one, which escapes the |.
Arrays.asList will convert the array returned by split to a list.
If you want to do this using characters...
- Get the whole string
- Read character by character into a new string
- If you find the delimiter, add new string to list. Empty new string.
- Repeat.
Is it what you are looking for ??There is a predefined function in String class.Make use of it
String original ="abc|xyz";
String[] resulted =original.split("\\|");//returns a String array
Play with the resulted array here.
Good luck.
来源:https://stackoverflow.com/questions/16461337/how-to-separate-specific-elements-in-string-java