Removing repeated characters in String

后端 未结 4 1644
半阙折子戏
半阙折子戏 2020-12-20 04:49

I am having strings like this \"aaaabbbccccaaffffddcfggghhhh\" and i want to remove repeated characters get a string like this \"abcadcfgh\".

A simplistic implementati

4条回答
  •  情歌与酒
    2020-12-20 05:47

    You can use Java's String.replaceAll() method to simply do this with a regular expression.

    String s = "aaaabbbccccaaffffddcfggghhhh";
    System.out.println(s.replaceAll("(.)\\1{1,}", "$1")) //=> "abcadcfgh"
    

    Regular expression

    (               group and capture to \1:
     .              any character except \n
    )               end of \1
    \1{1,}          what was matched by capture \1 (at least 1 times)
    

提交回复
热议问题