Removing repeated characters in String

后端 未结 4 1649
半阙折子戏
半阙折子戏 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:44

    You can do this:

    "aaaabbbccccaaffffddcfggghhhh".replaceAll("(.)\\1+","$1");
    

    The regex uses backreference and capturing groups.

    The normal regex is (.)\1+ but you've to escape the backslash by another backslash in java.

    If you want number of repeated characters:

    String test = "aaaabbbccccaaffffddcfggghhhh";
    System.out.println(test.length() - test.replaceAll("(.)\\1+","$1").length());
    

    Demo

提交回复
热议问题