All about C plus plus algorithms!

Tuesday 17 May 2016

Find and Replace words in a paragraph || C++ function || Char array practice

Limitations :
  • Hard coded paragraph
  • The word to be found and to be replaced with must be of the same lengths.
  • For those who have no idea of pointers, simple char array is used hence hard coded the size as well.
Code:
   

#include <iostream>
#include <conio.h>
using namespace std;

void mySearch(char para1[], int size, char find[], int fsize, int &index, int x)  //Search function
{
index = -1;
int i = 0;
if (find[i] == para1[x])   //para1 is the array that contains paragraph
                  //find contains the word to be found
int j = x, flag = 0;
for (i = i + 1; i < size && find[i] != '\0' && flag == 0; i++)
{
x++;
if (find[i] == para1[x])
{
;
}
else
flag = 1;  //if the complete word is not found ... breaks the loop

}
if (flag == 0)
{
index = i;  //if the complete word is found
}
}
}
char toReplace(char replace[], int size, char para[], int rsize, int index, int x1) //this function replaces
{
int i = index;
para[i] = replace[x1];  
return para[i];
}
int main()
{
char para[400] = "Cheating is the getting of a reward for ability by dishonest means or finding an easy way out of an unpleasant situation. It is generally used in situations to gain unfair advantage in a competitive situation. This broad definition will necessarily include acts of bribery, cronyism, sleaze, nepotism and any situation where individuals are given preference using inappropriate criteria.";  //hard coded para
cout << para << endl;  //displaying paragraph (optional)
char find[10], replace[10];
cout << "Find : ";
cin >> find;
cout << endl << "Enter the word to replace with : ";
cin >> replace;
cout << endl;
int index = 0, j = 0;
char w;

for (int i = 0; para[i] != '\0'; i++)
{
mySearch(para, 400, find, 10, index, i);
if (index != -1)
{
for (j; replace[j] != '\0'; j++)
{
w = toReplace(replace, 10, para, 400, index, j);
cout << w;
index++;
i++;
}
i--;
j = 0;
}
else
cout << para[i]; //displaying paragraph
}


system("pause");
return 0;
}

Thank you for reading! ^^



Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com