发现在string在处理这符串是很好用,就找了一篇文章放在这里了.. 用 string来代替char * 数组,使用sort排序算法来排序,用unique 函数来去重 #include <string>#include <iostream>using namespace std;int main(){ string strinfo="Please input your name:"; cout << strinfo ; cin >> strinfo; if( strinfo == "winter" ) cout << "you are winter!"<<endl; else if( strinfo != "wende" ) cout << "you are not wende!"<<endl; else if( strinfo < "winter") cout << "your name should be ahead of winter"<<endl; else cout << "your name should be after of winter"<<endl; strinfo += " , Welcome to China!"; cout << strinfo<<endl; cout <<"Your name is :"<<endl; string strtmp = "How are you? " + strinfo; for(int i = 0 ; i < strtmp.size(); i ++) cout<<strtmp[i]; return 0;} 5、find函数
以上函数都是被重载了4次,以下是以find_first_of 函数为例说明他们的参数,其他函数和其参数一样,也就是说总共有24个函数: size_type find_first_of(const basic_string& s, size_type pos = 0)size_type find_first_of(const charT* s, size_type pos, size_type n)size_type find_first_of(const charT* s, size_type pos = 0)size_type find_first_of(charT c, size_type pos = 0) 所有的查找函数都返回一个size_type类型,这个返回值一般都是所找到字符串的位置,如果没有找到,则返回string::npos。其实string::npos表示的是-1。即没找到就返回-1。例子如下:#include <string>#include <iostream>using namespace std;int main(){ string strinfo=" //*---Hello Word!......------"; string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int first = strinfo.find_first_of(strset); if(first == string::npos) { cout<<"not find any characters"<<endl; return -1; } int last = strinfo.find_last_of(strset); if(last == string::npos) { cout<<"not find any characters"<<endl; return -1; } cout << strinfo.substr(first, last - first + 1)<<endl;//string.substr是子串 return 0;}6、insert函数, replace函数和erase函数 string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串。例子:#include <string>#include <iostream>using namespace std;int main() { string strinfo="This is Winter, Winter is a programmer. Do you know Winter?"; cout<<"Orign string is :\n"<<strinfo<<endl; string_replace(strinfo, "Winter", "wende"); cout<<"After replace Winter with wende, the string is :\n"<<strinfo<<endl; return 0;} string.erase(pos,srclen);//srclen是删除的长度string.insert(pos,strdst); //pos是定位,strdst是插入的函数void string_replace(string & strBig, const string & strsrc, const string &strdst) { string::size_type pos=0; string::size_type srclen=strsrc.size(); string::size_type dstlen=strdst.size(); while( (pos=strBig.find(strsrc, pos)) != string::npos){ strBig.erase(pos, srclen); strBig.insert(pos, strdst); pos += dstlen; }} |
时间: 2024-10-08 20:50:40