How to check two string have same characters including special characters

后端 未结 6 1051
陌清茗
陌清茗 2021-01-25 04:41

I have two question

1) how can I check two shuffle string have same characters Like I have

var str1 = \"ansar@#//1\";
var str2 = \"@#//sanra1\";
         


        
6条回答
  •  生来不讨喜
    2021-01-25 05:08

    So I can't comment, because I don't have the ratings, but I tried Yuriy Yakym's solution (the second one, and a massive thank you Yuriy because I'd have struggled without that to work with in the beginning) and whilst it works for this example, if you add another 'a' say to str1, it won't show you that str2 doesn't actually have 3 'a's, because it's always going to reference the first appearance of the said character. In essence, you need to delete the found characters to ensure you are accounting for duplicates, or so it seems.

    I developed the below from Yuriy's code to get it working for me. Please test it yourself. Happy to be disagreed with, but it seems, it will log out everything (including duplicates) that appears in str1 but doesn't appear inside str2:

    const sorter = (str1, str2) => {
       const arr = str1.split(""); 
       const newArray = arr.filter((c) => {
          if (str2.indexOf(c) === -1) {
             return str2.indexOf(c) === -1 
          } else {
             str2 = str2.replace(c, '');
          }   
       })
       return newArray.join("");
    };
    
    console.log(sorter(str1, str2));
    

提交回复
热议问题