2013-10-28 131 views
1

代碼獲取用戶輸入(HTML標記)在下用字符替換字符串

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

gets(str); 

任務是具有newline("\n")

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

printf("%s", str); 

全部更換&nbsp; OCCURENCES上述代碼僅替換第一字符\n

查詢是如何將整個&nbsp;替換爲\n或如何將nbsp;的其餘部分設置爲空字符常量而不終止帶空指針字符串('\ 0')的字符串。

+0

是NBSP數組? – sukhvir

+0

@sukhvir這是str的一部分(用戶輸入使用獲取) – user1502952

+1

只是一個建議..不要使用'gets()'..用'fgets'代替 – sukhvir

回答

1

你快到了。現在只需使用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); 
+0

對不起,請您指定參數 – user1502952

+0

@ user1502952編輯,希望它有助於 – Zaffy

+0

這可以通過移動而不是所有東西來進行優化,但只能移到下一個' '。然後你從第二個移動到第三個10個字符等。 – aragaer

1

相反的memcpy的,你可以在字符直接設置爲「\ n」:*ptchr = '\n';和使用的memmove後向左移動行的其餘部分 - 您更換6個字符有1個,所以你必須移動由5個字符組成。

0

代碼

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