Here is the function prototype in my program:
void FindRepStr(char str[], const char findStr[], const char replaceStr[]);
It find the findStr[]
in str[]
and replace it with replaceStr[]
.
Here is my code:
void FindRepStr(char str[], const char findStr[], const char replaceStr[])
{
char *s = nullptr;
s = strstr(str,findStr); //s points to the first-time appear in str
char tmp[] ="";
//length equal
if(strlen(findStr)==strlen(replaceStr))
{
for(int i=0;i<strlen(findStr);i++)
{
if(replaceStr[i]=='\0' || s[i] =='\0')
break;
else
s[i] = replaceStr[i];
}
cout<<str<<endl;
}
else
{
//find shorter than replace
if(strlen(findStr)<strlen(replaceStr))
{
//!!!problem here!!!
strncpy(tmp,s,strlen(s)+1); // store the left part
for(int i=0;i<=strlen(replaceStr);i++)
{
if(replaceStr[i]=='\0') //if end of replace
{
s[i]='\0'; //make s(str) end here
break;
}
else
s[i] = replaceStr[i]; //if not end, give the value
}
}
//finder longer than replace
else
{
//...not finished yet
}
}
}
I haven't finished this but here after strncpy, I printed s and tmp for test and I found tmp is correctly copied, but s print out empty:
cout<<"s before strncpy:"<<s<<endl;
strncpy(tmp,s,strlen(s)+1);
cout<<"tmp after strncpy:"<<tmp<<endl;
cout<<"s after strncpy:"<<s<<endl;
But in simple test program I write, I found it won't be emptied:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char a[]="abc";
char b[]="defgh";
cout<<"a before:"<<a<<endl;
cout<<"b before:"<<b<<endl;
strncpy(a,b,strlen(b)+1);
cout<<"a after:"<<a<<endl;
cout<<"b after:"<<b<<endl;
return 0;
}
What went wrong in my program?
char tmp[] ="";
Here you are creating a character array with enough space to hold the string literal, including the terminating nul. Since the string literal is empty, this character array holds exactly one character.
If you write more than that (and you do), you enter the realm of undefined behavior. Basically you are dumping your strings all over random places in the stack; predictably, this doesn't end well.
You need to ensure your character array has enough space to do what you want.
Also, your program logic looks entirely broken. I don't see how that code is supposed to do what the function name suggests it should.