[STL]コンテナの初期化文字列、ステッチ、割り当て、見つけ、置き換え、比較、サブストリング、挿入、削除

A、文字列プロパティ

STL文字列は、典型的には、文字列を表すのに使用される文字列型です。文字列を使用する前に、文字の文字列は、一般に文字列とチャーは、示された文字列を表すために使用することができます。
文字列プロパティといえば、チャーだろう比較文字列タイプ:
1は、チャーは
、ポインタである文字列クラスである
文字列がchar *、文字列の管理をカプセル化し、char型で型容器。
2、文字列は実用的なメンバーメソッドの多くをカプセル化し
検索、コピーのコピー、削除、削除を見つけるために、置き換える置き換え、INSERT INSERT
3、関係なく、メモリの解放とのクロスボーダーの
文字列はchar管理
割り当てられたメモリを、価値によってコピーのすべての文字列、文字列クラスは、ように、クロスボーダー、クロスボーダーのコピーとの値を心配していない、の世話をします。
図4は、文字列と文字は、文字列の文字ターン交換可能である c_str()メソッドの文字列で提供します。

//string转char*
string str=“abcdefg”;
const char* cstr=str.c_str();
//char*转string
char* s=“abcdefg”;
string sstr(s);

二、文字列のコンテナの初期化、ステッチ、割り当ては、置き換え、検索と比較、サブストリング、挿入、削除

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

///////////////////////の1-初期化
ここに画像を挿入説明
ここに画像を挿入説明

void test01() {
	string s1;//调用无参构造
	string s2(10, 'a');
	string s3("abcdefg");
	string s4(s3);//拷贝构造

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;

}

2-割り当て//////////////////////
ここに画像を挿入説明

void test02() {
	string s1;
	string s2("appp");
	s1 = "abcdefg";
	cout << s1 << endl;
	s1 = s2;
	cout << s1 << endl;
	s1 = 'a';
	cout << s1 << endl;

	//成员方法 assign 进行赋值
	s1.assign("jkl");
	cout << s1 << endl;
}

3- //////////////////////値演算

void test03() {

	string s1 = "abcdefg";

	//重载[]操作符
	for (int i = 0; i < s1.size(); ++i) {
		cout << s1[i] << " ";
	}
	cout << endl;
	//at成员函数
	for (int i = 0; i < s1.size(); ++i) {
		cout << s1.at(i) << " ";
	}
	cout << endl;

	//区别:[]方式 如果访问越界,直接挂掉
	//		at方式 访问越界,抛出异常out_of_range;

	try {
		cout << s1.at(100) << endl;
	}
	catch(...){
		cout << "越界" << endl;
	}
}

4-スプライシング操作/////////////////////
ここに画像を挿入説明

void test04() {
	string s = "abcd";
	string s2 = "1111";
	s += "abcd";
	s += s2;
	cout << s << endl;//abcdabcd1111

	string s3 = "2222";
	s2.append(s3);//把s3加到s2后面
	cout << s2 << endl;// 11112222

	string s4 = s2 + s3;//把s3加到s2的后面
	cout << s4 << endl;//111122222222
}

//////////////////// 5検索と置換
ここに画像を挿入説明

void test05() {
	string s = "abcdefgsadasaafgddefgde";
	//查找第一次出现的位置
	int pos=s.find("fg");
	cout << "pos:"<<pos << endl;

	//查找最后一次出现的位置
	pos = s.rfind("fg");
	cout << "pos:" << pos << endl;
}

/////////////////////交換作業

void test06() {
	string s = "abcdefg";
	s.replace(0, 2, "111");
	cout << s << endl;
}

6-文字列比較////////////////////
ここに画像を挿入説明

void test07() {
	string s1 = "abcd";
	string s2 = "abce";
	if (s1.compare(s2) == 0) {
		cout << "字符串相等" << endl;
	}
	cout << "不相等" << endl;
}

////////////////// 7弦操作ストリング

void test08() {
	string s = "abcdefg";
	string sub=s.substr(1, 3);
	cout << sub << endl;
}

///////////////// 8文字列の挿入と削除
ここに画像を挿入説明

void test09() {
	string s = "abcdefg";
	s.insert(3, "111");//abc111defg
	cout << s << endl;

	s.erase(0, 2);//c111defg
	cout << s << endl;
}

nt main(void) {
	//test01();
	//test03();
	//test04();
	//test05();
	//test06();
	//test07();
	//test08();
	test09();
	return 0;
}
公開された57元の記事 ウォン称賛28 ビュー4133

おすすめ

転載: blog.csdn.net/weixin_41747893/article/details/102831889