C++文字列stringクラスの一般的な操作の詳細(一)【初期化、遍歴、接続】

2653 ワード

コードの例:
#include <iostream>
#include "string"

using namespace std;

//      
void strInit()
{
	cout << "      :"  <<endl;

	string s1 = "abcdefg";	//     1
	string s2("abcdefg");	//     2
	string s3 = s2;			//            s3
	string s4(7,'s');		//   7 s    

	cout << "s1 = "<< s1 << endl;
	cout << "s2 = "<< s2 << endl;
	cout << "s3 = "<< s3 << endl;
	cout << "s4 = "<< s4 << endl;
}

//     
void strErgo()
{
	cout << "     :"  <<endl;

	string s1 = "abcdefg";	//      
	
	//        
	cout << "1、        :"  <<endl;
	for (int i = 0; i < s1.length(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	//       
	cout << "2、       :"  <<endl;
	for(string::iterator it = s1.begin(); it!= s1.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	//  at()    
	cout << "3、  at()    :"  <<endl;
	for (int i = 0; i < s1.length(); i++)
	{
		cout << s1.at(i) << " ";		//             
	}
	cout << endl;
}

//           
void strConvert()
{
	cout << "           :"  <<endl;
	string s1 = "abcdefg";	//      

	cout << "string   char*:"  <<endl;
	//string   char*
	cout << s1.c_str() <<endl;	//s1.c_str()  s1 char *  

	cout << "char*  string  :"  <<endl;
	//char*  string  
	char buf[64] = {0};
	s1.copy(buf, 7);//  7   
	cout << buf <<endl;
}

//     
void strAdd()
{
	cout << "     :"  <<endl;

	cout << "  1:"  <<endl;
	string s1 = "123";
	string s2 = "456";
	s1 += s2;
	cout << "s1 = "<< s1 << endl;

	cout << "  2:"  <<endl;
	string s3 = "123";
	string s4 = "456";
	s3.append(s4);
	cout << "s3 = "<< s3 << endl;
}
int main()
{
	//   
	strInit();
	cout << endl;
	//  
	strErgo();
	cout << endl;
	//            
	strConvert();
	cout << endl;
	//     
	strAdd();
	cout << endl;
	system("pause");
	return 0;
}
プログラム実行結果:
      :
s1 = abcdefg
s2 = abcdefg
s3 = abcdefg
s4 = sssssss

     :
1、        :
a b c d e f g
2、       :
a b c d e f g
3、  at()    :
a b c d e f g

           :
string   char*:
abcdefg
char*  string  :
abcdefg

     :
  1:
s1 = 123456
  2:
s3 = 123456

       . . .