如何修剪字符串中的重复字符 [英] How to trim the duplicate char in a string

查看:70
本文介绍了如何修剪字符串中的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像1,2,2,3,3,3,4那样的字符串

我想剪掉重复的部分,然后把它变成1,2 ,3,4"

我该怎么办?

I have a string like "1,2,2,3,3,3,4"
I want to trim off the duplicate part, and make it to "1,2,3,4"
How can I do?

推荐答案

ad< ad@wfes.tcc.edu。 TW>写道:
ad <ad@wfes.tcc.edu.tw> wrote:
我有一个类似1,2,2,3,3,3,4的字符串
我想修剪掉重复的部分,并使其成为 1,2,3,4
我该怎么办?
I have a string like "1,2,2,3,3,3,4"
I want to trim off the duplicate part, and make it to "1,2,3,4"
How can I do?




最好的办法是拆分价值(例如用

String.Split)然后重建字符串,检查重复项

go(可能使用Hashtable记住哪些你已经

()* b $ b -

Jon Skeet - < sk *** @ pobox.com>
http://www.pobox.com/~skeet

如果回复小组,请不要给我发邮件



The best thing to do would be to split the values (e.g. with
String.Split) then rebuild the string, checking for duplicates as you
go (possibly using a Hashtable to remember which ones you''ve already
seen).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


ad写道:
我有一个类似1,2,2,3,3的字符串,3,4"
我想修剪掉复制的部分,并将其设为1,2,3,4
我该怎么办?
I have a string like "1,2,2,3,3,3,4"
I want to trim off the duplicate part, and make it to "1,2,3,4"
How can I do?



尝试使用此代码片段


string nstr ="" ;;

for(int i = 1; i< str.Length; i ++)

{

if(str [i]!= str [i-1])

nstr + = str [i];

}


Try with this snippet

string nstr = "";
for (int i = 1;i< str.Length;i++)
{
if (str[i] != str[i-1])
nstr += str[i];
}


dd< ne ***** @ here.com>写道:
dd <ne*****@here.com> wrote:
ad写道:
我有一个像1,2,2,3,3,3,4的字符串
我想修剪关闭重复部分,并使其成为1,2,3,4
我该怎么办?
I have a string like "1,2,2,3,3,3,4"
I want to trim off the duplicate part, and make it to "1,2,3,4"
How can I do?


尝试使用此片段

string nstr =" ;;
for(int i = 1; i< str.Length; i ++)
{
if(str [i]!= str [i-1])
nstr + = str [i];
}

Try with this snippet

string nstr = "";
for (int i = 1;i< str.Length;i++)
{
if (str[i] != str[i-1])
nstr += str[i];
}




不仅效率低(使用字符串连接方式
$ b不必要的$ b - 你应该使用StringBuilder来循环

连接),它也不会做什么是必需的。如果你看一下

测试字符串,在任何情况下都不会有一个字符后跟相同的

字符。如果你将i-1更改为

i-2,它会工作到*某个*范围,但如果副本中的任何一个出现在

非 - 相邻位置,或者如果值超过一个字符

宽。


-

Jon Skeet - < sk***@pobox.com>
http://www.pobox。 com / ~siget

如果回复小组,请不要给我发邮件



Not only is that inefficient (in terms of using string concatenation
unnecessarily - you should use a StringBuilder for looped
concatenation), it also doesn''t do what''s required. If you look at the
test string, in no case is one character followed by the same
character. It would work to *some* extent if you changed the i-1 to
i-2, but then it would still fail if either the duplicate came in a
non-adjacent position, or if the values were more than one character
wide.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


这篇关于如何修剪字符串中的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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