只显示字符串中的唯一字符一次

编程入门 行业动态 更新时间:2024-10-18 06:09:02
本文介绍了只显示字符串中的唯一字符一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字符串,我想要的重复字母,字母重复更多,然后一次只显示一次。例如我有一个字符串aaabbbccc我想要的结果是abc。到目前为止我的函数工作原理如下:如果信件不重复它没有显示如果它重复一次只显示一次(如果aa显示a)如果重复两次显示所有(如果aaa显示aaa)如果它的重复3次它显示6(如果aaaa显示aaaaaa)

I have a string with repeated letters i want, letter that are repeated more then once to show only once. for instance I have a string aaabbbccc i want the result to be abc. so far my function works like this: if the letter doesn't repeat its not shown if its repeated once its show only once (if aa shows a) if its repeated twice shows all(if aaa shows aaa) if its repeated 3 times it shows 6( if aaaa shows aaaaaa)

function unique_char(string){ var str_length=string.length; var unique=''; var count=0; for(var i=0; i<str_length; i++){ for(var j=i+1; j<str_length; j++){ if(string[i]==string[j]){ count++ unique+=string[i]; } } } return unique; } document.write( unique_char('aaabbbccc'))

函数必须在循环内,这是为什么第二个在第一个

function must be with loop inside a loop that's why the second for is inside the first

推荐答案

请先将其存储到数组,然后使用回答此处,然后重新加入,如下所示:

Convert it to an array first, then use the answer here, and rejoin, like so:

var nonUnique = "ababdefegg"; var unique = nonUnique.split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');

全部在一行中: - )

All in one line :-)

更多推荐

只显示字符串中的唯一字符一次

本文发布于:2023-11-29 12:37:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只显示   字符串   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!