字符串操作(连接、查找、截断、反转、大小写转换)

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);


你可能感兴趣的:(C-C++基础)