2013-08-19 32 views
7

我想在這樣一個特定的索引來改變一個C++字符串來改變字符串最好的方法:C++,在一個特定的指數

string s = "abc"; 
s[1] = 'a'; 

是下面的代碼是否有效?這是一個可接受的方式來做到這一點?

我沒有找到它說,這是任何有效的參考:

http://www.cplusplus.com/reference/string/string/

這表示,通過「超負荷[]字符串操作」,我們可以進行寫操作。

+0

是的,一點問題都沒有。如果您確實需要參考,請參閱C++ 11標準的第21.4.5/2節。 –

+5

呃。在C++ 11中,這實際上是由於標準的缺陷而被禁止的,並且你在技術上*必須使用's.begin()[1] ='a';'但這不值得擔心。 – Potatoswatter

+0

你*找到了一個說明它是有效的參考,儘管cplusplus.com通常是不合標準的並且經常過時。考慮到這個聯繫,目前還不清楚你還想知道什麼。 – Potatoswatter

回答

9

是,下面的C++程序:

#include <iostream> 

int main() { 
    std::string s = "abc"; 
    s[1] = 'a'; 
    std::cout << s; 
} 

打印aac。如果字符串s是空白字符串,則可能會意外寫入未分配的內存。 C++會讓你這樣做,並導致未定義的行爲。

的安全的方式做,這是使用string::replacehttp://cplusplus.com/reference/string/string/replace

+1

安全版本將使用string :: replace http://www.cplusplus.com/reference/string/string/replace/ – Chris

1

是的。你鏈接的網站有一個關於它的網頁。你也可以在執行邊界檢查的函數中使用。

http://www.cplusplus.com/reference/string/string/operator%5B%5D/

+1

@Patatoswatter爲什麼?關鍵是程序員可以選擇使用邊界檢查。 –

+0

@NeilKirk:我認爲它正在發生變化,因爲每個人都假設*邊界檢查正在完成,並且不知道'at()'。 – cHao

+2

@Patatoswatter檢查什麼?該函數或者用有效位置調用(考慮*一個* null終止符)或者行爲未定義。請參閱要求條款。 –

1

是你寫的代碼是有效的。您也可以嘗試:

string num; 
cin>>num; 
num.at(1)='a'; 
cout<<num; 

**Input**:asdf 
**Output**:aadf 

std :: replace也可以用來替換文字記錄器。這裏是參考鏈接http://www.cplusplus.com/reference/string/string/replace/

希望這會有所幫助。

0

你可以使用字符串來實現這一

string s = "abc"; 
    string new_s = s.substr(0,1) + "a" + s.substr(2); 
    cout << new_s; 
    //you can now use new_s as the variable to use with "aac" 
相關問題