Showing unique characters in a string only once

后端 未结 13 2260
-上瘾入骨i
-上瘾入骨i 2020-12-31 20:38

I have a string with repeated letters. I want letters that are repeated more than once to show only once. For instance I have a string aaabbbccc i want the result to be abc.

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 20:47

    Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):

    function unique_char(string){
    
        var str_length=string.length;
        var unique='';
    
        for(var i=0; i

    In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.

    I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.

提交回复
热议问题