簡體   English   中英

用C中的字符替換字符串

[英]replacing string with character in C

該代碼需要用戶輸入(html標記)

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

gets(str);

任務是替換所有&nbsp; newline("\\n")

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

printf("%s", str);

上面的代碼僅將\\n替換為第一個字符。

查詢是如何替換整個&nbsp; \\n或如何設置其余的nbsp; 到空字符常量之類的東西,而不用空指針('\\ 0')終止字符串。

你快到了。 現在,只需使用memmove將內存向左移動到新行。

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

代替memcpy,您可以直接將字符設置為'\\ n': *ptchr = '\\n'; 然后使用memmove將剩余的行向左移動-您用1替換了6個字符,因此必須將行移動5個字符。

    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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM