string中成员函数的相关用法
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
//string 不是关键字 而是一个类
int _tmain(int argc, _TCHAR* argv[])
{
string s = "china";
string s2 = "is great";
s += s2;//string的连接
cout << s << endl;
cout <<"s.size()= "<<s.size() << endl; //利用.size()方法求长度大小
cout << "s.length()= " << s.length() << endl;
//string的比较
if (s == s2)
cout << "s=s2" << endl;
else if (s > s2)
cout << "s>s2" << endl;
else
cout << "s<s2" << endl;
//对字符串中下标的操作
cout << s[3] << endl;
cout << (s.c_str())[3] << endl;
s[3] = 'w';
cout << s << endl;
cout << s.at(1) << endl; //.at(int) 函数能返回string中下标为int的数据
//string和char* 类型之间的转换 .c_str()
char buf[1024];
strcpy(buf, s.c_str());
//利用.c_str()的方法将string类型返回成char* 类型 赋值给字符数组buf
cout << "***" << buf << endl;
//string之间的交换
string str = "china";
string str2 = "xxxx";
cout << str << str2 << endl;
str.swap(str2); //利用.swap(s)的方法将俩个string交换
cout << str << str2 << endl;
//查找字符串中的字符或者字符串 find函数
//int find(char c,int pos=0);
//int find(char* s,int pos=0);
string ss = "china";
int n = ss.find('i', 0); //也可以查找字符串中的字符串如 find('in',0)
//表示从这个字符串的0下标开始查找
//第一次出现'i'字符的下标 并返回其下标 如果找不到则返回-1
cout << "n=" << n << endl;
//stirng 类型数组 (高效、且不会造成空间浪费)
string sArray[10] = {
"0",
"1",
"22",
"333",
"4444",
"55555",
"666666",
"7777777",
"88888888",
"999999999",
};
for (int i = 0; i<10; i++)
{
cout << sArray[i] << endl;
}
return 0;
}