1:字符串连接
string strSample1("Hello");
string strSample2("String!");
string strSample3("strSample3");
strSample1+= strSample2;
strSample1.append(strSample3);
2:字符串查找
string strSample("Good dayString! Today is beautiful!");
size_t nOffset = strSample.find("day",2);//从下标2开始查找
if(nOffset != npos)
{
cout << "在下标:" << nOffset << "找到了day!" << endl;
}
else
{
cout << "没找到!" << endl;
}
找出所有的day
size_t nSubstringOffset = strSample.find("day",0);//从头开始查找
while(nSubstringOffset != npos)
{
cout << "在下标:" << nSubstringOffset << "找到了day!" << endl;
size_t nSearchOffset= nSubstringOffset+1;
nSubstringOffset = strSample.find("day",nSearchOffset);
}
3:字符串截断
string strSample("Good dayString! Today is beautiful!");
strSample.erase(5,18);//Good is beautiful!
4:字符串反转
string strSample("Good dayString! Today is beautiful!");
reverse(strSample.begin(),strSample.end());
5:字符串大小写转换
string strSample("Good dayString! Today is beautiful!");
transform(strSample.begin(),strSample.end(),strSample.begin(),toupper);
string strSample1("Hello");
string strSample2("String!");
string strSample3("strSample3");
strSample1+= strSample2;
strSample1.append(strSample3);
2:字符串查找
string strSample("Good dayString! Today is beautiful!");
size_t nOffset = strSample.find("day",2);//从下标2开始查找
if(nOffset != npos)
{
cout << "在下标:" << nOffset << "找到了day!" << endl;
}
else
{
cout << "没找到!" << endl;
}
找出所有的day
size_t nSubstringOffset = strSample.find("day",0);//从头开始查找
while(nSubstringOffset != npos)
{
cout << "在下标:" << nSubstringOffset << "找到了day!" << endl;
size_t nSearchOffset= nSubstringOffset+1;
nSubstringOffset = strSample.find("day",nSearchOffset);
}
3:字符串截断
string strSample("Good dayString! Today is beautiful!");
strSample.erase(5,18);//Good is beautiful!
4:字符串反转
string strSample("Good dayString! Today is beautiful!");
reverse(strSample.begin(),strSample.end());
5:字符串大小写转换
string strSample("Good dayString! Today is beautiful!");
transform(strSample.begin(),strSample.end(),strSample.begin(),toupper);
6:buf中查询字符e
int main()
{
char buf[] = " hellow";
char *p = strchr(buf,'e');
if (NULL == p)
{
printf("查询失败\n");//查询失败返回NULL
}
else
{
printf("p = %s\n",p);//buf中查询字符e,存在返回p的地址,ellow
}
}
7:buf中查询字串ell
int main()
{
char buf[] = " hellow";
char *p = strstr(buf,"ell");
if (NULL == p)
{
printf("查询失败\n");//查询失败返回NULL
}
else
{
printf("p = %s\n",p);//buf中查询字串ell,存在返回p的地址,ellow
}
}
8:字符串分割
int main()
{
char buf[] = "abd,mike,efg,hellow";
char tmp[100];
strcmp(tmp,buf);
char *p;
p = strtok(tmp,","); // 第一次调用
while (p != NULL)
{
printf("p = %s\n",p);// p = abd,p = mike,p = efg,p = hellow
p = strtok(NULL,","); //第二次起,第一个参数需要写NULL
}
}
9:字符串替换
Void StringReplace(string &strBase, string strSrc, string strDes)
{
string::size_type pos = 0;
string::size_type srcLen = strSrc.size();
string::size_type desLen = strDes.size();
pos=strBase.find(strSrc, pos);
while ((pos != string::npos))
{
strBase.replace(pos, srcLen, strDes);
pos=strBase.find(strSrc, (pos+desLen));
}
}