发现在string在处理这符串是很好用,就找了一篇文章放在这里了..
用 string来代替char * 数组,使用来排序,用来去重
1、Define
string s1 = "hello";
string s2 = "world";
string s3 = s1 + "," + s2 +"!\n";
2、append
s1 += ",shanshan\n";
3、Compare
if(s1 == s2)
.....
else if(s1 == "hello")
.....
4、 string 重载了许多操作符,包括 +, +=, <,
=,
, [], <<, >>等,正式这些操作符,对字符串操作非常方便
#include #include using namespace std; int main(){ string strinfo="Please input your name:"; cout << strinfo ; cin >> strinfo; if( strinfo == "winter" ) cout << "you are winter!"<
5、find函数
由于查找是使用最为频繁的功能之一,string 提供了非常丰富的查找函数。其列表如下:
函数名 | 描述 |
find | 查找 |
rfind | 反向查找 |
find_first_of | 查找包含子串中的任何字符,返回第一个位置 |
find_first_not_of | 查找不包含子串中的任何字符,返回第一个位置 |
find_last_of | 查找包含子串中的任何字符,返回最后一个位置 |
find_last_not_of | 查找不包含子串中的任何字符,返回最后一个位置 |
以上函数都是被重载了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 #include 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"< #include using namespace std; int main() { string strinfo="This is Winter, Winter is a programmer. Do you know Winter?"; cout<<"Orign string is :\n"< <