How to split a string, but also keep the delimiters?

前端 未结 23 2795
我在风中等你
我在风中等你 2020-11-21 06:32

I have a multiline string which is delimited by a set of different delimiters:

(Text1)(DelimiterA)(Text2)(DelimiterC)(Text3)(DelimiterB)(Text4)
23条回答
  •  醉梦人生
    2020-11-21 07:02

    If you can afford, use Java's replace(CharSequence target, CharSequence replacement) method and fill in another delimiter to split with. Example: I want to split the string "boo:and:foo" and keep ':' at its righthand String.

    String str = "boo:and:foo";
    str = str.replace(":","newdelimiter:");
    String[] tokens = str.split("newdelimiter");
    

    Important note: This only works if you have no further "newdelimiter" in your String! Thus, it is not a general solution. But if you know a CharSequence of which you can be sure that it will never appear in the String, this is a very simple solution.

提交回复
热议问题