string

[機能]

  文字列を保持するクラスです.比較演算子による比較や,+ 演算子による結合が可能です.

[使用方法]
#include <string>
using namespace std;
string 変数名;
		
[メンバー関数等]

[演算子の多重定義]
    +  ==  !=  <  >
		

[使用例]

  1. string の使用方法です.
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
    	char str[10];
    	string str1 = "abcde";
    	string str2 = str1, str3 = "bcdef";
    	string::iterator it1, it2;
    					// 文字列のコピー
    	str1.copy(str, 3, 2);
    	str[3] = '\0';
    	cout << "コピーされた結果 " << str << endl;
    					// 文字列の比較
    	cout << "比較  str1 = " << str1 << ", str2 = " << str2 << ", str3 = " << str3 << endl;
    	if (str2 == str1)
    		cout << "   str2 == str1\n";
    	if (str2 <= str2)
    		cout << "   str2 <= str3\n";
    					// 文字列の結合
    	str1 += (" " + str2);
    	cout << "文字列の結合結果: " << str1 << endl;
    					// 部分文字列
    	cout << str1 << " の 4 文字目から 5 文字\n";
    	cout << "   " << str1.substr(3, 5) << endl;
    	cout << "   ";
    	for (int i1 = 3; i1 < 8; i1++)
    		cout << str1[i1];
    	cout << endl;
    	cout << "   ";
    	for (int i1 = 3; i1 < 8; i1++)
    		cout << str1.at(i1);
    	cout << endl;
    	const char *c_str = str1.c_str();
    	cout << "   ";
    	for (int i1 = 3; i1 < 8; i1++)
    		cout << c_str[i1];
    	cout << endl;
    					// 検索
    	cout << str1 << " から文字列 cd の検索結果: " << str1.find("cd") << endl;
    					// 挿入
    	cout << "挿入(元の文字列: " << str1 << ")\n";
    	str2 = "-+*+-";
    	str3 = str1;
    	cout << "   " << str3.insert(2, str2, 0, 3) << endl;
    	str3 = str1;
    	it1  = str3.begin() + 2;
    	str3.insert(it1, 3, '*');
    	cout << "   " << str3 << endl;
    					// 削除
    	cout << "削除(元の文字列: " << str1 << ")\n";
    	str3 = str1;
    	cout << "   " << str3.erase(2, 3) << endl;
    	str3 = str1;
    	it1  = str3.begin() + 2;
    	it2  = it1 + 3;
    	str3.erase(it1, it2);
    	cout << "   " << str3 << endl;
    					// 置換
    	cout << "置換(元の文字列: " << str1 << ")\n";
    	str2 = "-+*+-";
    	str3 = str1;
    	cout << "   " << str3.replace(3, 5, str2, 0, 3) << endl;
    	str3 = str1;
    	it1  = str3.begin() + 3;
    	it2  = it1 + 5;
    	cout << "   " << str3.replace(it1, it2, str2) << endl;
    					// 交換
    	cout << "交換\n";
    	str2 = "-+*+-";
    	cout << "   " << str1 << "     " << str2 << endl;
    	str1.swap(str2);
    	cout << "   " << str1 << "     " << str2 << endl;
    
    	return 0;
    }
    
    (出力)
    
    コピーされた結果 cde
    比較  str1 = abcde, str2 = abcde, str3 = bcdef
       str2 == str1
       str2 <= str3
    文字列の結合結果: abcde abcde
    abcde abcde の 4 文字目から 5 文字
       de ab
       de ab
       de ab
       de ab
    abcde abcde から文字列 cd の検索結果: 2
    挿入(元の文字列: abcde abcde)
       ab-+*cde abcde
       ab***cde abcde
    削除(元の文字列: abcde abcde)
       ab abcde
       ab abcde
    置換(元の文字列: abcde abcde)
       abc-+*cde
       abc-+*+-cde
    交換
       abcde abcde     -+*+-
       -+*+-     abcde abcde
    			
[参照]

deque

ホームページ 目次 演習解答例目次 付録目次 索引