如何使用StringBuilder从字符串(不是数组)中删除重复项? [英] How to remove duplicates from string (not array) without using StringBuilder?

查看:664
本文介绍了如何使用StringBuilder从字符串(不是数组)中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我的程序,我需要从用户给我的字符串中删除重复的字符。我引用了其他问题,但他们都使用 StringBuilder 来删除重复项。但是,使用 StringBuilder Set

I am working with my program and I need to remove repeated characters from a string given to me by the user. I referenced other questions, but they are all using StringBuilder to remove duplicates. However, is there any way to remove duplicates without turning the string into an array, using StringBuilder and Set?

我还没有学到这些,所以我不太了解他们。我可以得到一些帮助吗?

I haven't learnt those yet, so I don't understand them very well. Could I get some help?

例如,如果用户在中开始运行,则结果应为 hapyroling

For example, if user types in happyrolling the result should be hapyroling.

推荐答案

从你的例子来看,你想删除重复的字符

It seems from your example you want to remove repeated characters (not words).

您可以使用正则表达式查找重复并将其删除:

You can use regex to find the repeats and remove them:

str = str.replaceAll("(.)\\1+", "$1");

这个正则表达式捕获每个字符,但只有通过使用相同的字符后跟才能匹配被捕集团。替换是捕获的字符,所以例如xx被替换为x

This regex captures every character but only matches when followed by the same character by using a back reference to the captured group. The replacement is the captured character, so for example "xx" is replaced by "x"

这篇关于如何使用StringBuilder从字符串(不是数组)中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆