문제

The code takes user input(html tag)

ex:
<p> The content is &nbsp; text only &nbsp; inside tag </p>

gets(str);

Task is to replace all &nbsp; occurences with a newline("\n")

while((ptrch=strstr(str, "&nbsp;")!=NULL)
{
  memcpy(ptrch, "\n", 1);
}

printf("%s", str);

The code above replaces only first character with \n.

Query is how to replace entire &nbsp; with \n or how to set rest of nbsp; to something like empty character constant without terminating string with null pointer('\0').

도움이 되었습니까?

해결책

You're almost there. Now just use memmove to move the memory left to the new line.

char str[255];
char* ptrchr;
char* end;

gets(str); // DANGEROUS! consider using fgets instead
end = (str + strlen(str));

while( (ptrch=strstr(str, "&nbsp;")) != NULL)
{
    memcpy(ptrch, "\n", 1);
    memmove(ptrch + 1, ptrch + sizeof("&nbsp;") - 1, end-ptrchr);
}

printf("%s", str);

다른 팁

Instead of memcpy you could directly set the character to '\n': *ptchr = '\n'; And after that use memmove to move the rest of the line left - you replaced 6 characters with 1, so you have to move the line by 5 characters.

Code

    char * ptrch = NULL;
    int len =0;
    while(NULL != (ptrch=strstr(str, "&nbsp;")))
    {
      len = strlen(str) - strlen(ptrch);
      memcpy(&str[len],"\n",1);
      memmove(&str[len+1],&str[len+strlen("&nbsp;")],strlen(ptrch ));   
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top