How to find and print the common characters (letters) in different strings with TypeScript

2 Answers

0 votes
function getCommonCharacters(str1: any, str2: string) {
    let strcommon: string = "";
     
    for (let i in str1) {
        if (str2.includes(str1[i])) {
            if (! strcommon.includes(str1[i])) {
                strcommon += str1[i];
            }
        }
    }
     
    return strcommon;
}
 
const str1: string = "c c++ c# java go";
const str2: string = "python nodejs php typescript";
 
let strcommon: string = getCommonCharacters(str1, str2);
 
console.log("Same letters are: " + strcommon);
 
 
 
  
/*
run:
   
"Same letters are: c jo"
   
*/

 



answered Jan 27, 2024 by avibootz
0 votes
function getCommonCharacters(str1: string, str2: string) {
    let set1 = new Set(str1);
    let set2 = new Set(str2);
     
    let strcommon = new Set([...set1].filter(x => set2.has(x)));
      
    return [...strcommon].join('');;
}
 
const str1: string = "c c++ c# java go";
const str2: string = "python nodejs php typescript";
 
let strcommon: string = getCommonCharacters(str1, str2);
 
console.log("Same letters are: " + strcommon);
 
 
 
  
/*
run:
   
"Same letters are: c jo"
   
*/

 



answered Jan 27, 2024 by avibootz
...