C++で文字列の最後に文字を追加します
この簡単な記事では、C++で文字列の最後に文字を追加するさまざまな方法について説明します。
1.使用する push_back()
関数
推奨されるアプローチは、標準を使用することです push_back()
関数。charsに対してオーバーロードされ、文字列の末尾に文字を追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.push_back(ch); std::cout << s; return 0; } |
2.使用する +=
オペレーター
使用することもできます string::operator+=
、charsのためにオーバーロードされ、内部的に push_back()
関数。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s += ch; std::cout << s; return 0; } |
3.使用する append()
関数
別のもっともらしいアプローチは、 append()
以下に示すように、文字列の最後に文字の単一コピーを追加する関数:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.append(1, ch); std::cout << s; return 0; } |
4.使用する std::stringstream
関数
もう1つの優れた代替手段は、文字列ストリームを使用して文字列と他の数値タイプを変換することです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "C+"; char ch = '+'; std::stringstream ss; ss << s << ch; ss >> s; std::cout << s; return 0; } |
5.使用する insert()
関数
最後に、 insert()
文字列の指定された位置に文字の単一コピーを挿入する関数。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "C+"; char ch = '+'; s.insert(s.length(), 1, ch); std::cout << s; return 0; } |
これで、C++の文字列の最後に文字を追加することができます。
こちらも参照: