Hi, I need to write a function that replaces selected character in string with another character.
The function takes char pointer and two char variables as parameters and returns int(number of changes made in the array)
So the prototype would look like following int replace(char * str, char c1, char c2);
this is code I managed to get to work, although I'm sure it can be done better way.
#include<iostream>
#include<cstring>
usingnamespace std;
int replace(char * str, char ch1, char ch2);
int main()
{
char * str="Palko vybehni na scenu, bez teba to nema cenu";
char e='e'; //the character that needs to be changed
char star='*'; // character to which the needed character will be changed
cout << "String " << str << "\n will be changed to:\n";
int changes=replace(str, e, star);
cout << str << "\nNumber of changes made: " << changes << endl;
cin.get();
cin.get();
return 0;
}
int replace(char * str, char ch1, char ch2)
{
int changes=0; //how many times the function replaces characters
char * newStr= newchar[strlen(str)+1]; //here will be stored the modified str array
int n=0; //variable that will be used as index variable for newStr
while(*str!='\0')
{
if(*str==ch1) //does *str equals to ch1?
{
newStr[n]=ch2; //replace it with ch2 then
changes++; //pretty obvious
}
else
{
newStr[n]=*str; //if does not, simply copy the original character from str
}
str++; //setting address to another character
n++; //setting next index for newStr
}
//at the end of the cycle the variable 'n' has value of the size of str array
newStr[n]='\0'; //ending the character array
cout << newStr << endl;
return changes;
}
In my first attempt I wanted to change the original array sent to function, so it would look like this:
So the actual str in main function would be modified, but it gives me an exception for the line *str=ch2; saying Acces violating writing location..
Apparently I'm missing some knowledge, therefore I would like to be corrected. And also, could the function be done simpler way than mine?
Thank you.
Thank you for reply,
and if I wanted to give the user option to input his own string?
How would that be done?
I know it can be done using string type, but what about char type, beside of creating a char array that is large enough just to make sure the user input string will fit in.