ホームに戻る
出典 :
関連 :
目次 :
char [n] 型( char 配列)を用いた string の初期化( char [n] から string への変換)
char [n] で string を初期化(および代入)できる。
// 初期化に使用する文字列( char [n] )
const char* input = "Rock'n Roll never dies.";
// 以下はいずれも等価
// (コンストラクタ引数に input を与えて初期化)
std::string str1 = input;
std::string str2(input);
std::string str3 {input};
// string に char [n] を代入することも可能
std::string str4;
str4 = input;
// 各変数の値を出力
std::cout << "input : " << input << std::endl;
std::cout << "str1 : " << str1 << std::endl;
std::cout << "str2 : " << str2 << std::endl;
std::cout << "str3 : " << str3 << std::endl;
std::cout << "str4 : " << str4 << std::endl;
実行結果
input : Rock'n Roll never dies.
str1 : Rock'n Roll never dies.
str2 : Rock'n Roll never dies.
str3 : Rock'n Roll never dies.
str4 : Rock'n Roll never dies.
初期化の際に char [n] の一部(部分文字列)を抽出することも可能である。
const char* input = "Rock'n Roll never dies.";
// input の先頭から 6 文字を抽出する
std::string str5(input, 6);
// input の 7 文字目から 4 文字を抽出する
std::string str6(input, 7, 4);
// 各変数の値を出力
std::cout << "input : " << input << std::endl;
std::cout << "str5 : " << str5 << std::endl;
std::cout << "str6 : " << str6 << std::endl;
実行結果
input : Rock'n Roll never dies.
str5 : Rock'n
str6 : Roll
string から char* への変換( c_str() )
string のメンバ関数 c_str() を用いることで、char* を得ることができる。
printf() などのCライブラリ関数は string を引数に取ることができないため、この方法で char* に変換して用いる。
// string 型変数の宣言・初期化
std::string str = "THE HIGH-LOWS"
// printf() に string を直接渡す ⇒ エラー
// printf("%s\n", str);
// char* 型に変換して printf() に渡す ⇒ OK
printf("%s\n", str.c_str());
実行結果
THE HIGH-LOWS