learn CPP, the code is an exercise of string substitution, in which the expression
p = strstr (pdjm)! = NULL in the while loop will report an error at this point.
if you change this sentence to ((p = strstr)! = NULL), there will be no problem if you execute the left first.
feels like it was executed first on the right. What I don"t understand is why the sentence strstr! = NULL is wrong.
the Visual Studio 2017 compiler used is the default configuration has not been changed,
-sharpdefine _CRT_SECURE_NO_WARNINGS
-sharpinclude <stdio.h>
-sharpinclude <stdlib.h>
-sharpinclude <string.h>
-sharpinclude <ctype.h>
//
int replaceSubstr(char *src,char **dst,char *sub, char *new_sub)
{
char *out = NULL;
char *p = NULL;
char *q = NULL;
int sub_len = 0;
int new_sub_len = 0;
if (src == NULL || dst == NULL || new_sub == NULL) {
fprintf(stderr, "src == NULL || dst == NULL || new_sub == NULL");
return -1;
}
out = (char *)malloc(sizeof(char *) * 4096); //4096 * char*
if (out == NULL)
{
fprintf(stderr, "malloc out error\n");
return -1;
}
memset(out, 0, 4096); //4096
p = src; // p
q = p; // q
sub_len = strlen(sub); //
new_sub_len = strlen(new_sub); //
while ( p = strstr(p, sub) != NULL) { // strstr
//
//q p-qsub
strncat(out, q, p - q); //out
strncat(out, new_sub, new_sub_len); //sub
p += sub_len; // p
q = p; //q
if (*p == "\0") { // *p0
break;
}
}
if (*q != "\0") {
strncat(out, q,( src + strlen(src) - q ));
}
*dst = out;
//free();
return 0;
}
int main(void)
{
char *str = "213abcd123231abcd213321asdabcd123214abcd";
char *dst = NULL;
replaceSubstr(str,&dst,"abcd","XX");
printf("%s\n", dst);
return 0;
}