2013-03-26 75 views
0

字符串我有一個類似代碼如下 -替換特定的字符在C++

Value = "Current &HT"; //this is value 
void StringSet(const char * Value) 
{ 
    const char *Chk = NULL; 
    Chk = strpbrk(Value,"&"); 
    if(Chk != NULL) 
    {  
    strncpy(const_cast<char *> (Chk),"&amp",4) 
    } 
} 

在上面的代碼中,我想,以取代「&」從價值「& amp.It工作正常,如果我有」 &「單個字符,但在目前的情況下strpbrk()返回」 & HT「並在下面的函數strncpy整個」 & HT「將被替換。

現在我想知道方法,通過它,我只能從代替單個字符字符串

+3

爲什麼你會不會爲這個使用'的std :: string'?它有一個'替換'功能。 – chris 2013-03-26 06:28:19

+0

我想使用它,但是因爲我正在處理已定義的程序,所以我在某些限制下不使用std :: string。 – user987316 2013-03-26 06:31:51

回答

1

我想你需要一些臨時數組來保存字符串過去&,然後用原始字符串替換&並將臨時數組添加到原始數組中。這裏修改了上面的代碼,我相信你可以用strstr代替strchr它接受char *作爲第二個參數。

void StringSet(char * Value) 
{ 
    char *Chk = NULL,*ptr = NULL; 
    Chk = strchr(Value,'&'); 
    if(Chk != NULL) 
    { 
    ptr = Chk + 1; 
    char* p = (char*)malloc(sizeof(char) * strlen(ptr)); 
    strcpy(p,ptr); 
    Value[Chk-Value] = '\0'; 
    strcat(Value,"&amp"); 
    strcat(Value,p); 
    free(p); 
    } 
} 

感謝 尼拉吉瑞斯

0

你不應該修改一個常量字符串,當然也不能修改字符串。雖然這是很多很多更好地使用std::string,而不是處理資源管理自己,一個辦法是分配一個新的C風格的字符串,並返回一個指向它的指針:

char *StringSet(const char *Value) { 
    char buffer[256]; 
    for (char *p = (char*)Value, *t = buffer; p[0] != 0; p++, t++) { 
    t[0] = p[0]; 
    if (p[0] == '&') { 
     t[1] = 'a'; t[2] = 'm'; t[3] = 'p'; 
     t += 3; 
    } 
    t[1] = 0; 
    } 
    char *t = new char[strlen(buffer)+1]; 
    strcpy(t, buffer); 
    return t; 
} 
0
string str="Current &HT"; 
str.replace(str.find('&'),1,"&amp"); 
+0

「我正在處理一個已經定義的程序,我受到一些限制,不使用std :: string」 – Shoe 2013-03-26 06:53:30

2

不能代替一個在C風格的字符串中有幾個字符,因爲你無法知道C風格的字符串有多少空間可用來添加新字符。您只能通過分配一個新字符串並將舊字符串複製到新字符串來執行此操作。像這樣的東西

char* StringSet(const char* value) 
{ 
    // calculate how many bytes we need 
    size_t bytes = strlen(value) + 1; 
    for (const char* p = value; *p; ++p) 
     if (*p == '&') 
      bytes += 3; 
    // allocate the new string 
    char* new_value = new char[bytes]; 
    // copy the old to the new and replace any & with &amp 
    char* q = new_value; 
    for (const char* p = value; *p; ++p) 
    { 
     *q = *p; 
     ++q; 
     if (*p == '&') 
     { 
      memcpy(q, "amp", 3); 
      q += 3; 
     } 
    } 
    *q = '\0'; 
    return new_value; 
} 

但這是可怕的代碼。你真的應該使用std :: string。

+0

如果你正在做所有的工作來計算最終的字符串大小和迭代複製,你可以很容易地修復'value' (使用向後迭代),這似乎是海報代碼的意圖。當然,這有緩衝溢出的潛力。 +1「你真的應該使用std :: string」。 – 2013-03-26 06:57:53

+0

@TonyD當我說你不知道你有多少空間時,那就是我的觀點。另外還有用字符串文字調用這個函數的問題。 – john 2013-03-26 07:00:47

+0

非常好的一點,鑑於你選擇的妥協看起來不錯。乾杯。 – 2013-03-26 08:08:43