How to separate specific elements in string java

你离开我真会死。 提交于 2019-12-02 23:43:17

问题


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;
}

回答1:


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.




回答2:


If you want to do this using characters...

  1. Get the whole string
  2. Read character by character into a new string
  3. If you find the delimiter, add new string to list. Empty new string.
  4. Repeat.



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!