只显示字符串中的唯一字符一次 [英] Showing unique characters in a string only once

查看:139
本文介绍了只显示字符串中的唯一字符一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想要的重复字母,字母重复更多,然后一次只显示一次。例如我有一个字符串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 :-)

这篇关于只显示字符串中的唯一字符一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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