简体   繁体   中英

Extract unique characters from a string with keeping whitespace between strings

How do I extract unique letter occurrences in a string, including all spaces?

The problem with my code is that it only returns the first occurrence of the space:

function unique_char(str1) {
  var str = str1;
  var uniql = "";
  for (var x = 0; x < str.length; x++) {

    if (uniql.indexOf(str.charAt(x)) == -1) {
      uniql += str[x];

    }
  }
  return uniql;
}
console.log(unique_char("the fox news newspaper"));

this prints to console:

the foxnwspar

but my desired output is:

the fox nws par

Any help will be appreciated.

Thanks

Add logical OR to check if the char is whitespace

if (uniql.indexOf(char) == -1 || char == ' ') 

See working snippet below:

 function unique_char(str) { var uniql = ""; for (var x = 0; x < str.length; x++) { var char = str.charAt(x); if (uniql.indexOf(char) == -1 || char == ' ') { uniql += str[x]; } } return uniql; } document.write(unique_char("the fox news newspaper")); 

if you're trying to preserve the whitespace, first check to see if it is ' ' , else then check if it's unique.

 function unique_char(str1) { var str = str1; var uniql = ""; for (var x = 0; x < str.length; x++) { if (str.charAt(x) === ' '){ uniql += str[x]; } else if (uniql.indexOf(str.charAt(x)) == -1) { uniql += str[x]; } } return uniql; } console.log(unique_char("the fox news newspaper")); 

this prints to console:

the fox nws par

why not just remove the space?

 function unique_char(str1) { var str = str1.replace(/\\s+/g, '');; var uniql = ""; for (var x = 0; x < str.length; x++) { if (uniql.indexOf(str.charAt(x)) == -1) { uniql += str[x]; } } return uniql; } alert(unique_char("the fox news newspaper")); 

I would go for using hashsets as their lookup is O(1), instead of N as indexOf() is. JavaScript has a nice object called Set . Alternatively you can use objects as their keys are unique by nature.

For the real question, just skip the char in the string which is a space (equal to ' ' )

function unique_char(str1) {
  var result = {};
  for (var i = 0; i < str1.length; i++) {
    if (str1[i] != ' ') result[str1[i]] = 1;
  }
  return Object.keys(result).join("");
}

console.log(unique_char("the fox news newspaper"));

You can init uniql with a space character and delete it at the end

function unique_char(str1) {
   var str = str1;
   var uniql = " ";
   for (var x = 0; x < str.length; x++) {

     if (uniql.indexOf(str.charAt(x)) == -1) {
     uniql += str[x];

  }
 }
 return uniql[1:];
}
console.log(unique_char("the fox news newspaper"));
if (uniql.indexOf(str.charAt(x)) == -1) {
  uniql += (str[x] !== ' ') ? str[x] : '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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