Advertisement
krstoilo

Similarity

Oct 20th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. std::string recordWordsFromText (std::string & text){
  6.  
  7. std::istringstream istr(text);
  8.  
  9. std::string onlyWords;
  10.  
  11. istr >> onlyWords;
  12.  
  13. for(int i = 0; i < onlyWords.size(); i++){
  14.  
  15.     if(onlyWords[i] == ',' ||
  16.        onlyWords[i] == '.' ||
  17.        onlyWords[i] == ';' ||
  18.        onlyWords[i] == '!' ||
  19.        onlyWords[i] == '?'){
  20.  
  21.         onlyWords.replace(i,1," ");
  22.     }
  23. }
  24.  
  25. }
  26. return onlyWords;
  27.  
  28. }
  29.  
  30.  
  31. bool lettersMatch (std::string recordedWord, std::string singleWord, int similarityPercent){
  32.  
  33.     int len = (int)recordedWord.size();
  34.     double matchingLetter = 0;
  35.  
  36.     for(int i = 0; i < len; i++){
  37.  
  38.         if(recordedWord[i] == singleWord[i]){
  39.  
  40.             matchingLetter ++;
  41.         }
  42.     }
  43.  
  44.     double matchingPercent = (matchingLetter / len) * 100;
  45.  
  46.     if(similarityPercent <= matchingPercent){
  47.  
  48.         return true;
  49.  
  50.     }
  51.  
  52.  
  53.     return false;
  54.  
  55.  
  56. }
  57.  
  58.  
  59.  
  60. bool areSimilar (std::string recordedWord, std::string singleWord, int similarityPercent){
  61.  
  62.     int recLen = recordedWord.size();
  63.     int singleLen = singleWord.size();
  64.  
  65.     if(   recLen == singleLen
  66.        && recordedWord[0] == singleWord[0]
  67.        && lettersMatch(recordedWord,singleWord,similarityPercent) == 1){
  68.  
  69.         return true;
  70.     }
  71.  
  72.         return false;
  73.  
  74. }
  75.  
  76.  
  77. int main(){
  78.  
  79.     std::string text;
  80.     std::string word;
  81.     int similarityPercent = 0;
  82.  
  83.     getline(std::cin,text);
  84.     std::cin >> word >> similarityPercent;
  85.  
  86.     std::string newStr = recordWordsFromText(text);
  87.  
  88.     std::cout << newStr << std::endl;
  89.  
  90.     std::istringstream istr(newStr);
  91.  
  92.     std::string currentWord;
  93.  
  94.     int similarWords = 0;
  95.  
  96.     while(istr >> currentWord){
  97.  
  98.         if(areSimilar(currentWord,word,similarityPercent) == 1){
  99.  
  100.             similarWords++;
  101.         }
  102.     }
  103.  
  104.     std::cout << similarWords;
  105.  
  106.  
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement