1

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').

2
  • @sukhvir that's part of str (user input using gets) Commented Oct 28, 2013 at 8:31
  • 1
    just a suggestion ..don't use gets() .. use fgets instead Commented Oct 28, 2013 at 8:35

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Sorry could you please specify the parameters also
This could be optimized somewhat by moving not everything but only up to next &nbsp;. Then you move from second to third by 10 characters etc.
Why strcpy is going to work? We're dealing with overlapping memory here.
@aragaer No. Overlapping may be only when you move memory to right, not to left.
@Zaffy doesn't it depend on implementation?
|
1

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.

Comments

0

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 ));   
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.