Awesome Hacks!

プログラミング初心者なので地道に勉強していきます。分からない人の立場から整理していきます。

STL_string

【プログラム】

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

int main(){
	string s1;				// クラスと同じ。引数なければデフォルトコンストラクタで空文字
	string s2("string222");	// 「test」をコンストラクタに渡す場合。
	string s3("333string");	// 「test」をコンストラクタに渡す場合。
							// vectorやmap同様、最初に大きさ(文字列の長さを決めなくても格納できる)

	cout << "s1             : " << s1 << endl;
	cout << "s2             : " << s2 << endl;
	cout << "s3             : " << s3 << endl;

	string s4 = s2;			// stringクラス(便宜的にそう呼ぶことにする)は
	s2 = s3;				// 自分でコピーコンストラクタや代入演算子を定義しなくても
							// 使うことができる
	cout << "\ns1             : " << s1 << endl;
	cout << "s2(s3を代入)   : " << s2 << endl;
	cout << "s3             : " << s3 << endl;
	cout << "s4(s2で初期化) : " << s4 << endl;

	string s5 = s3 + s4;
	cout << "s5(s3 + s4)    : " << s5 << endl;	// operator「+」も定義済みなので使用可能
	cout << "s5のサイズ     : " << s5.size() << endl;

	string s6("what are you doing now?");
	if(s6.find("saying") == string::npos){
		cout << "文字列「saying」がありません。" << endl;
	} else {
		cout << "文字列「saying」がありました。" << endl;
	}
	if(s6.find("doing") == string::npos){
		cout << "文字列「doing」がありません。" << endl;
	} else {
		cout << "文字列「doing」がありました。" << endl;
	}

	return 0;
}

 

$ testString
s1             : 
s2             : string222
s3             : 333string

s1             : 
s2(s3を代入)   : 333string
s3             : 333string
s4(s2で初期化) : string222
s5(s3 + s4)    : 333stringstring222
s5のサイズ     : 18
文字列「saying」がありません。
文字列「doing」がありました。
$