How to separate specific elements in string java

前端 未结 3 2070
面向向阳花
面向向阳花 2021-01-27 18:25

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

3条回答
  •  天命终不由人
    2021-01-27 18:52

    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.

提交回复
热议问题