C++--String容器

 

	string str1 = "abcdefg";
	rfind 是從右往左查早 find 是從左往右查找
	cout << str1.find("e") << endl;
	cout << str1.rfind("ef") << endl;

	//字符串替換//
	str1.replace(1, 3, "1111");
	cout << str1 << endl;

	//字符串比較
	string str2 = "abcdfg";
	if (str1.compare(str2) == 0)
	{
		cout << "str1 == str2" << endl;
	}

	//訪問字符串元素
	for (int i = 0;i < str1.size();i++)
		cout << str1[i] << " " << endl;
	for (int i = 0;i < str1.size();i++)
		cout << str1.at(i)<< " " << endl;

	//修改字符串元素
        str1[0] = 'x';
	str1.at(1) = 'x';
	cout << str1 << endl;

	//字符串插入
	str1.insert(1, "111");
	cout << str1 << endl;

	//字符串刪除
	str1.erase(1, 3);//第一個位置開始刪除三個
	cout << str1 << endl;

	//從字符串中獲取子串 

	string substr = str1.substr(1, 3);//從第一個元素開始截取3個
	cout << substr << endl;

	//實用操作 截取用戶名
	string email = "[email protected]";
	int pos = email.find('@');

	string UseName = email.substr(0, pos);
	cout << UseName << endl;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章