How to separate specific elements in string java

前端 未结 3 2030
面向向阳花
面向向阳花 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.

    0 讨论(0)
  • 2021-01-27 18:59

    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.

    0 讨论(0)
  • 2021-01-27 19:06

    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.
    0 讨论(0)
提交回复
热议问题