I'm quite stuck at this point. Ultimately I want to send sentence to replaceSubstring then return the same sentence with "the" replaced with "that". I know I should be using pointers, but I'm not sure where and why exactly. Any advice?
The errors I'm getting are:
Ch12_08.cpp: In function ‘char replaceSubstring(char*, char*, char*)’:
Ch12_08.cpp:16: error: request for member ‘strstr’ in ‘sent’, which is of non-class type ‘char*’
Ch12_08.cpp:17: error: invalid conversion from ‘char*’ to ‘char’
Ch12_08.cpp:18: error: invalid conversion from ‘char*’ to ‘char’
Ch12_08.cpp: In function ‘int main()’:
Ch12_08.cpp:30: error: expected primary-expression before ‘]’ token
Here's the code I'm working with..
#include <iostream>
#include <cstring> // Needed for strstr to work
using namespace std;
char replaceSubstring(char sent[], char oldW[], char newW[]){
char *strPtr = NULL;
strPtr = &sent.strstr(sent, oldW);
*strPtr = newW;
return sent;
}
int main()
{
char sentence[35] = "the dog jumped over the fence";
char oldWord[5] = "the";
char newWord[6] = "that";
char newSentence[35] = {NULL};
wcout << "The original sentence is: " << sentence << endl;
newSentence[] = replaceSubstring(sentence, oldWord, newWord);
return 0;
}
Thanks in advance!
The error message is telling you exactly what is wrong:
strstris not a member function ofchar *.char *is not a class type.Rather,
strstris just a plain function. This will probably work better for you:Once you've found where
oldWis instrPtr, you will need to copynewWoveroldW. IfnewWandoldWare the same length that shouldn't be difficult. If they might be different lengths (as they seem to be in your example), you have your work cut out for you.In any case, the line you have after
strstrwill not do what you want. You need a loop to copy characters, or similar.And finally, you can't return a character array from your function like that. You need to pass
newSentenceas an argument to the function if you want your function to fill that array.Part of me wonders why you're even trying this with C strings when
std::stringmakes this so much nicer...