Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 一般的な文字列メソッド | テキストデータ型
C++データ型

book一般的な文字列メソッド

メニューを表示するにはスワイプしてください

追加

インデックスを使って文字列の末尾に新しい文字を追加することはできません。しかし、この目的のために便利な .append() メソッドがあります。

append.h

append.h

copy
1
str.append("added part");

連結

もう一つの方法は + 演算子を使うことです。これは文字列に適用すると連結を行います。

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "Code"; str = str + "finity"; // or str += "finity" std::cout << str << std::endl; }

また、.append() ではできない、テキストを先頭や両端に追加することも可能。

main.cpp

main.cpp

copy
12345678
#include <iostream> int main() { std::string str = "finity"; str = "code" + str + ".com"; std::cout << str << std::endl; }

挿入

.insert() メソッドを使用して、特定の位置に新しいテキストを文字列へ挿入可能。

insert.h

insert.h

copy
1
str.insert(pos, "text to add");

pos パラメータで指定された位置に新しいテキストが追加される。

新しいテキストは、指定した位置に現在ある文字のに挿入されます。このメソッドは、新しい文字列を作成せずに文字列を動的に変更する際に便利です。

置換

文字列の一部を別の文字列に置き換えることもできます。これは .replace() メソッドを使用して実現できます。

replace.h

replace.h

copy
1
str.replace(start, n, "new text");

ここで start は置換する最初の要素のインデックスを意味し、n は置換する部分の長さを表します。

以下は .replace() の動作を示すGIFです。

削除

.erase() メソッドを使用して文字列の一部を削除することもできます。これは、文字列から特定の文字や部分文字列を削除する必要がある場合に便利です。

erase.h

erase.h

copy
1
str.erase(start, n);

n パラメータが start から残りの文字列の長さと同じかそれ以上の場合、start 以降のすべての文字が削除されます。

start および n パラメータは .replace() メソッドと同様に機能し、文字列の柔軟な変更を可能にします。

main.cpp

main.cpp

copy
123456789101112131415161718192021
#include <iostream> int main() { std::string str = "finity"; str.append(".com"); // finity to finity.com std::cout << str << std::endl; str = "in" + str; // finity.com to infinity.com std::cout << str << std::endl; str.insert(2, "de"); // infinity.com to indefinity.com std::cout << str << std::endl; str.replace(0, 2, "co"); // indefinity.com to codefinity.com std::cout << str << std::endl; str.erase(10, 4); // codefinity.com to codefinity std::cout << str << std::endl; }
question mark

文字列 Hello の先頭に str を追加するコードはどれか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  4
some-alt