Replace occurrence of one character with another coderinme

Replace occurrence of one character with another coderinme

We shall now write a program which will replace the occurrence of one character with another in the string given by the user. Also this will count and display the total number of such replacements made.
For this we need to write a class that will represent a string.
This class would include Member functions like the following:
readstr() that will read the string.
showstr() that will display the string.
int replace(char c1,char c2): that replaces every occurrence of character c1 with character c2 in the string and returns the total replacements made.
Let us now begin with C++ codes.
Write a C++ program to use this class.

#include<iostream.h>
#include<conio.h>
#define MAX 50
class String
{
char str[MAX];
public:
void readstr()
{
cout &lt;&lt; &quot;Enter the string: &quot;;
cin.getline(str,25);
}
void show()
{
cout&lt;&lt; endl &lt;&lt; &quot;The string is: &quot; &lt;&lt; str &lt;&lt; endl;
}
int replace(char ch1,char ch2)
{
int n,i,count=0;
n=strlen(str);
for(i=0;i&lt;n;i++)
{
if(str[i]==ch1)
{
str[i]=ch2;
count++;
}
}
return count;
}
};
int main()
{
String str;
char ch1,ch2;
int count;
str.readstr();
cout&lt;&gt;ch1;
cout&lt;&gt;ch2;
count=str.replace(ch1,ch2);
cout&lt;&lt;&quot;number of replacement: &quot;&lt;&lt;count&lt;&lt;endl;
str.show();
getch();
return 0;
}

For more programs in C++, visit our C++ Coder Archives

Replace occurrence of one character with another coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.