How to remove duplicate characters in a string using regex?

前端 未结 2 729
滥情空心
滥情空心 2021-01-20 02:19

I need to replace the duplicate characters in a string. I tried using

outputString = str.replaceAll(\"(.)(?=.*\\\\1)\", \"\");

This replac

2条回答
  •  长发绾君心
    2021-01-20 02:45

    It seems like your code is leaving the last character, so how about this?

    outputString = new StringBuilder(str).reverse().toString();
    // outputString is now hiah
    outputString = outputString.replaceAll("(.)(?=.*\\1)", "");
    // outputString is now iah
    outputString = new StringBuilder(outputString).reverse().toString();
    // outputString is now hai
    

提交回复
热议问题