2017-06-14 48 views
2

在C,我們能夠做到這一點的指針:轉移在C++字符串

char *str; 
scanf("%s", str); // lets say that we enter "Hello" 
str = str + 2; 
printf("%s", str); // and the answer would be "llo" 

有沒有這樣的事情在C++處理字符串數據類型在O(1)的時間?

編輯:這是給我這個錯誤 - >

error: invalid operands to binary expression ('string' (aka 'basic_string<char, 
    char_traits<char>, allocator<char> >') and 'int') 
str = str + 1; 

EDIT2:我跑這個代碼,並得到了上面的錯誤 - >

string str = "Hello"; 
str = str + 1; 
cout << str << endl; 
+3

相同的代碼會在C++中也有未定義的行爲。 –

+0

@GAURANGVYAS是的,我一上傳問題就意識到了。我想用字符串數據類型來做到這一點。 –

+0

@NeilButterworth不,字符串數據類型。對不起,我編輯了這個問題。 –

回答

4
#include <iostream> 
#include <string> 
using namespace std; 

int main() { 
    string s = "foobar"; 
    cout << &s[s.size() - 2] << endl; 
    cout << &s[3] << endl; 

} 
+1

人們還可以提到'at(...)'功能,它確保給定的索引位置是一個有效的位置,即使這沒有明確要求。 – NOhs

+0

謝謝你,很多人都低估了這個問題。也許是因爲我沒有正確解釋這個問題。我認爲這個問題在我第一次編輯後很清楚,但至少我得到了答案。 –

+0

@MrZ你能解釋更多嗎?謝謝。 –