文字列を分析する私のコードは、整数で誤った位置数を出力しています。結果は最初は整数 1 つずれており、文字列に文字を挿入すると、文字を 1 つだけ追加したにもかかわらず、位置の値が 2 つ変化します。コードは次のとおりです。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
string s1 = "Hey, what's up?";
cout << s1.length() << endl; // should be 14 positions, not 15 if starting at 0
cout << s1.insert(1, "k") << endl;
s1 = s1.insert(1, "k");
cout << s1.length() << endl; //should be 15, not 17
system("pause");
return 0;
}
.length()
が正しい桁数を印刷しない理由を教えてください。