SHARE
TWEET

Untitled

a guest Dec 12th, 2019 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. int indexOf(char word[100], char str[1001])
  5. {
  6.     int n = strlen(str);
  7.     int s = strlen(word);
  8.  
  9.     if(s > n)
  10.     {
  11.         return -1;
  12.     }
  13.  
  14.     for (int i = 0; i < n; i++)
  15.     {
  16.         if(str[i] == word[0] && s <= n - i)
  17.         {
  18.             bool areEqual = true;
  19.  
  20.             for (int j = 1; j < s; j++)
  21.             {
  22.                 if(str[i + j] != word[j])
  23.                 {
  24.                     areEqual = false;
  25.                     break;
  26.                 }
  27.             }
  28.  
  29.             if(areEqual)
  30.             {
  31.                 return i;
  32.             }
  33.         }
  34.     }
  35.  
  36.     return -1;
  37. }
  38.  
  39. void strReplace(char str[1001], char result[1001], int index, char replaceWord[100], int oldWordLength)
  40. {
  41.     int n = strlen(replaceWord);
  42.  
  43.     for (int i = 0; i < index; i++)
  44.     {
  45.         result[i] = str[i];
  46.     }
  47.  
  48.     int j = 0;
  49.     for (int i = index; i < index + n; i++)
  50.     {
  51.         result[i] = replaceWord[j++];
  52.     }
  53.  
  54.     int resultLength = strlen(str);
  55.  
  56.     if(oldWordLength < n)
  57.     {
  58.         resultLength += n - oldWordLength;
  59.     }
  60.     else if(oldWordLength > n)
  61.     {
  62.         resultLength -= oldWordLength - n;
  63.     }
  64.    
  65.     int k = index + oldWordLength;
  66.     for (int i = index + j; i < resultLength; i++)
  67.     {
  68.         result[i] = str[k++];
  69.     }
  70. }
  71.  
  72. using namespace std;
  73.  
  74. int main()
  75. {
  76.  
  77.     char str[1001], result[1001];
  78.     cin >> str;
  79.     char word[100], replaceWord[100];
  80.     cin >> word >> replaceWord;
  81.  
  82.     int index = indexOf(word, str);
  83.  
  84.     if(index != -1)
  85.     {
  86.         strReplace(str, result, index, replaceWord, strlen(word));
  87.         cout << result << endl;
  88.     }
  89.     else
  90.     {
  91.         cout << str << endl;
  92.     }
  93.  
  94.     return 0;
  95. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top