简体   繁体   English

使用 javascript 在字符串中查找唯一字符

[英]To find unique characters in a string using javascript

Write a JavaScript program to find the unique characters in a string.编写一个 JavaScript 程序来查找字符串中的唯一字符。 The function uniqueCharacters must take a string as its argument and return the same after removing all the characters that appear more than once in the string. function uniqueCharacters 必须将字符串作为其参数,并在删除字符串中多次出现的所有字符后返回相同的值。 This is the main function.这是主要的function。

The function modifyString is the sub-function. function modifyString 是子函数。 This is invoked from within the function uniqueCharacters with the same string as the argument.这是从 function uniqueCharacters 中调用的,其字符串与参数相同。 This function will remove all the white space characters & convert the entire string to lower case and return the same to the caller.此 function 将删除所有空白字符并将整个字符串转换为小写并将其返回给调用者。

Note: You may verify the correctness of your function by invoking it from within console.log注意:您可以通过在 console.log 中调用 function 来验证它的正确性

console.log(uniqueCharacters("Welcome to the Javascript course"));

Where am I going wrong?我哪里错了? My code (below) isn't working correctly.我的代码(如下)无法正常工作。 The output should be: welcomthjavsripu . output 应该是: welcomthjavsripu

function modifyString(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

function uniqueCharacters(str)
{
   modifyString(str);
   var str1=str;
   var uniql= "";
   for(var x=0;x<str1.length;x++)
   {
       if(uniql.indexOf(str1.charAt(x))==-1)
       {
           if(str.charAt(x) === ' ')
           {
               continue;
           }
           uniql += str1[x];
       }
   }
   return uniql;
}
console.log(uniqueCharacters("Welcome to the Javascript course"));

I see two issues with your code:我发现您的代码有两个问题:

  • First you need to replace modifyString(str) with str = modifyString(str)首先,您需要将modifyString(str)替换为str = modifyString(str)
  • Second you only call toLower on the first character of your string, but you expect your whole string to be lowercase.其次,您只在字符串的第一个字符上调用 toLower,但您希望整个字符串都是小写的。 The modifyString function should simply be return str.toLowerCase(); modifyString function 应该简单地return str.toLowerCase();

I would use the approach of counting characters with Map and then filter them.我会使用 Map 计数字符的方法,然后过滤它们。

 function uniqueCharacters(str) { const uniqChar = new Map(); const result = [] for(const character of str) { if(uniqChar.has(character)) { uniqChar.set(character, uniqChar.get(uniqChar) + 1) } else { uniqChar.set(character,1) } } uniqChar.forEach((val,key) => { if(val === 1) result.push(key) }) return result; } console.log(uniqueCharacters("AbaacddeR"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM