您好,欢迎来到六九路网。
搜索
您的当前位置:首页字符串函数

字符串函数

来源:六九路网
BSOI

部分String函数 用法说明与示例

水平有限,故仅译极少部分(估计有不少错误)。

更多内容见原文:http://cplusplus.com/reference/string/string/

Oliver Q 28 Jan. 2008

1

BSOI

目录

前言................................................................................................................................................... 3 正文................................................................................................................................................... 3

构造字符串 ............................................................................................................................... 3 “+”运算符 ................................................................................................................................. 4 “=”运算符 ................................................................................................................................. 5 size函数 ................................................................................................................................... 6 length函数 ................................................................................................................................ 6 capacity函数 ............................................................................................................................ 6 max_size函数 ........................................................................................................................... 7 resize函数 ................................................................................................................................ 7 reserve函数 .............................................................................................................................. 8 clear函数 .................................................................................................................................. 9 empty函数 .............................................................................................................................. 10 “[ ]”运算符 ............................................................................................................................. 10 at函数 ..................................................................................................................................... 11 “+=”运算符 ............................................................................................................................. 11 assign函数 .............................................................................................................................. 12 append函数 ............................................................................................................................ 13 insert函数 ............................................................................................................................... 14 erase函数 ............................................................................................................................... 15 replace函数 ............................................................................................................................ 15 swap函数 ............................................................................................................................... 17 find函数 ................................................................................................................................. 17 rfind函数 ................................................................................................................................ 18 substr函数 .............................................................................................................................. 19 比较字符串大小 ..................................................................................................................... 19

2

BSOI

前言

字符串是一种特别为处理字符序列设计的、特殊的容器;

C++字符串不像传统的C字符串那样仅仅是一系列的字符内容。与其他出C++容器一样,C++字符串是一个类成员,具有许多内建的新特性,使得C++字符串具有更多功能,且操作更直观。

正文

构造字符串

explicit string ( );

string ( const string& str );

string ( const string& str, size_t pos, size_t n = npos ); string ( const char * s, size_t n ); string ( const char * s ); string ( size_t n, char c );

创建字符串并初始化内容。

不同的创建函数形式允许通过不同的方法初始化字符串:

explicit string ( );

创建空字符串。

string ( const string& str );

创建字符串,并将内容赋值为与str相同。

string ( const string& str, size_t pos, size_t n = npos );

字符串内容为str子串的副本,这一子串从位置pos开始,长度n个字符(n小于字符串的最大长度)。

string ( const char * s, size_t n );

字符串内容与字符序列s前n个字符相同。 string ( const char * s );

字符串内容是从一个以null结束的字符序列(C字符串)中拷贝而来的。字符序列的长度由第一个null标记决定。这一形式可以用来通过字符串常量初始化字符串。 string ( size_t n, char c );

字符串内容由字符c填充n次产生。

3

BSOI

示例程序:

// string constructor #include #include using namespace std; int main () { // constructors used in the same order as described above: string s1; string s5 (\"Initial string\"); string s2 (s5); string s3 (s5, 8, 3); string s4 (s5, 8); string s6 (10, 'x'); 输出示例: string s7a (10, 42); string s7b (s5.c_str(), s5.c_str()+4); cout << \"s1: \" << s1 << \"\\ns2: \" << s2 << \"\\ns3: \" << s3; cout << \"\\ns4: \" << s4 << \"\\ns5: \" << s5 << \"\\ns6: \" << s6; cout << \"\\ns7a: \" << s7a << \"\\ns7b: \" << s7b << endl; return 0; }

输出: s1:

s2: Initial string s3: str s4: Initial s5: Initial string s6: xxxxxxxxxx s7a: ********** s7b: Init “+”运算符

string operator+ (const string& lhs, const string& rhs); string operator+ (const char* lhs, const string& rhs); string operator+ (char lhs, const string& rhs);

string operator+ (const string& lhs, const char* rhs); string operator+ (const string& lhs, char rhs);

返回一个由lhs和rhs的内容合并在一起的字符串。

因为左侧参数lhs的多样性,这个函数执行时被视为全局运算符“+”的重载。 返回值:由lhs与rhs连接而成的新字符串。

4

BSOI

示例程序:

// adding strings #include #include using namespace std; main () { string firstlevel (\"com\"); string secondlevel (\"cplusplus\"); string scheme (\"http://\"); string hostname; string url; hostname = \"www.\" + secondlevel + '.' + firstlevel; url = scheme + hostname; cout << url << endl; return 0; }

输出: http://www.cplusplus.com

“=”运算符

string& operator= ( const string& str ); string& operator= ( const char* s ); string& operator= ( char c );

通过复制的方式为当前字符串指定新的内容,原有的内容会丢失。 与assign函数功能相似,但assign函数提供更多的功能。 参数:str:字符串类型,新的内容将应用于该字符串;

s:指针,指向一个以null结束的字符序列(C字符串),其内容将被拷贝到当前字符串。

c:字符,字符串内容将被指定为这个字符。

示例程序:

// string assigning #include #include using namespace std; int main () { string str1, str2, str3; str1 = \"Test string: \"; // c-string 5 str2 = 'x'; // single character str3 = str1 + str2; // string cout << str3 << endl; return 0; BSOI

输出: Test string: x

size函数

size_t size() const;

返回一个字符串的长度(即字符个数)。 返回值size_t是一个无符号整型数。

程序示例: // string::size #include #include using namespace std; int main () { string str (\"Test string\"); cout << \"The size of str is \" << str.size() << \" characters.\\n\"; return 0;

输出:

} The size of str is 11 characters.

length函数

size_t length() const;

length函数是size函数的别名,详见size函数。

capacity函数

size_t capacity ( ) const; 返回字符串占用的储存空间大小。

6

BSOI

注意,此函数返回的值并不一定等于字符串内容的长度(字符串内容长度可用size或length获得),而是往往大于后者。capacity函数的返回值也不是字符串所占空间的上限,如有请求,字符串所占空间可以增加。

字符串所能容纳的最大长度由函数max_size获得。

max_size函数

size_t max_size ( ) const;

返回字符串可容纳的最多的字母数量。 返回值size_t是一个无符号整型数。

程序示例(max_size、size、length、capacity函数的比较): // comparing size, length, capacity and max_size #include #include using namespace std; int main () { string str (\"Test string\"); cout << \"size: \" << str.size() << \"\\n\"; cout << \"length: \" << str.length() << \"\\n\"; cout << \"capacity: \" << str.capacity() << \"\\n\"; cout << \"max_size: \" << str.max_size() << \"\\n\"; return 0; }

输出: size: 11 length: 11 capacity: 15 max_size: 4294967291 resize函数

void resize ( size_t n, char c ); void resize ( size_t n );

强制规定字符串的长度为n个字符。

如果n小于现有字符串的长度,则前n个字符会保留,余下的字符会被丢弃。 如果n大于现有字符串的长度,则在字符串后追加字符c,以使其长度达到n。

第二种用法,实际上是在调用resize(n,char()),所以在n大于字符串现有长度,而又没有传递第二个参数时,默认填充null字符。

参数:n:新的字符串长度(以字符数计算);

7

BSOI

c:用来填充额外空间的字符。

程序示例:

// resizing string #include #include using namespace std; int main () { size_t sz; string str (\"I like to code in C\"); cout << str << endl; sz=str.size(); str.resize (sz+2,'+'); cout << str << endl; str.resize (14); cout << str << endl; 输出: I like to code in C I like to code in C++ I like to code return 0; } reserve函数

void reserve ( size_t res_arg=0 );

请求改变字符串所占的空间大小。

请求使字符串所占的储存空间大小至少变为res_arg。 这个函数可以使字符串所占的储存空间变小或变大,不过要注意函数执行后的字符串储存空间大小并不一定等于res_arg,而是大于或等于该参数。而且,这个函数绝不会裁剪字符串的实际内容。如果你要那样做,参看risize函数或clear函数。 参数:res_reg:要保留的最少的空间大小。

程序示例: // string::reserve #include #include #include using namespace std; 输出: int main () { string str; size_t filesize; ifstream file (\"test.txt\ filesize=file.tellg(); str.reserve(filesize); file.seekg(0); while (!file.eof()) { str += file.get(); } cout << str; return 0; 8 BSOI

这个程序用reserve函数保留足够的空间以逐字符读取并储存整个文件。通过这种方式,我们将字符串空间预先申请为整个文件的大小,避免使str的大小在每次输入字符的大小超过原有空间大小后都被自动重新分配。

clear函数

void clear();

清空字符串。

使用此函数清除字符串的所有内容,并将其大小设为0。

程序示例: // string::clear #include #include using namespace std; int main () { string str; char c; cout << \"Please type some lines of text. Enter a period to finish:\\n\"; do { c=cin.get(); str += c; if (c=='\\n') { cout << str; str.clear(); } } while (c!='.'); 用户每输入一行,程序就要重复一次,直到有句号(英文period,‘.’字符)输入。用户每输入一个回车符,就会触发出clear函数,清空当前字符串。

return 0; } 9

BSOI

empty函数

bool empty ( ) const;

返回一个字符串是否为空,或者说,它的大小是否为零。

这个函数不会改变字符串内容,如需清空字符串,参见clear函数。

程序示例: // string::empty #include #include using namespace std; int main () { string content; string line; cout << \"Please introduce a text. Enter an empty line to finish:\\n\"; do { getline(cin,line); content += line + '\\n'; } while (!line.empty()); cout << \"The text you intorduced was:\\n\" << content; return 0; }

程序会要求用户输入字符,并按行储存,直到用户输入一个空行。

“[ ]”运算符

const char& operator[] ( size_t pos ) const; char& operator[] ( size_t pos );

获得字符串中的一个字符。 返回字符串中pos位置的字符。 该函数实际调用data()[pos]。

at成员函数与该函数功能相同,不过,at函数会对范围进行校验。

参数:pos:字符串中待读取的字符的位置,注意,字符串第一个字符位置为0。

程序示例: // string::operator[] #include #include using namespace std; int main () { string str (\"Test string\"); int i; for (i=0; i < str.length(); i++) { cout << str[i]; } return 0; 10 BSOI

程序通过访问字符串,逐字符输出字符串内容。

at函数

const char& at ( size_t pos ) const;

char& at ( size_t pos );

与“[ ]”运算符类似,不过当pos超范围时会产生out_of_range异常,大家可自行实验,详见“[ ]”运算符。

“+=”运算符

string& operator+= ( const string& str ); string& operator+= ( const char* s ); string& operator+= ( char c );

追加一个参数字符串的副本。

新字符串的内容为现有字符串后跟上参数内容的结果。 与append函数相似,但后者提供更多功能。 参数:str:要追加的字符串。

s:指向以null结束的字符序列(C字符串)的指针; c:要追加的字符。

程序示例: // string::operator+= #include #include using namespace std; int main () { string name (\"John\"); string family (\"Smith\"); name += \" K. \"; // c-string name += family; // string name += '\\n'; // character cout << name; return 0; } 11 BSOI

输出:

John K. Smith

assign函数

string& assign ( const string& str );

string& assign ( const string&, size_t pos, size_t n ); string& assign ( const char* s, size_t n ); string& assign ( const char* s ); string& assign ( size_t n, char c );

为字符串内容赋值。 字符串内容取决于传递给改函数的值:

assign ( const string& str );

将内容赋值为与str相同。

assign ( const string&, size_t pos, size_t n );

字符串内容为str子串的副本,这一子串从位置pos开始,长度n个字符(n小于字符串的最大长度)。

assign ( const char* s, size_t n );

字符串内容与字符序列s前n个字符相同。 assign ( const char* s );

字符串内容是从一个以null结束的字符序列(C字符串)中拷贝而来的。字符序列的长度由第一个null标记决定。这一形式可以用来通过字符串常量为字符串赋值。 assign ( size_t n, char c );

字符串内容由字符c填充n次产生。

程序示例:

// string::assign #include #include using namespace std; int main () { string str; string base=\"The quick brown fox jumps over a lazy dog.\"; // used in the same order as described above: str.assign(base); cout << str << endl; str.assign(base,10,9); cout << str << endl; // \"brown fox\" str.assign(\"pangrams are cool\ cout << str << endl; // \"pangram\" str.assign(\"c-string\"); 12 cout << str << endl; // \"c-string\" str.assign(10,'*'); cout << str << endl; // \"**********\" str.assign(10,0x2D); BSOI

输出:

The quick brown fox jumps over a lazy dog. brown fox pangram c-string ********** ---------- fox jumps over

append函数

string& append ( const string& str );

string& append ( const string& str, size_t pos, size_t n ); string& append ( const char* s, size_t n ); string& append ( const char* s ); string& append ( size_t n, char c );

在当前字符串后面追加字符(串)。

参数的含义与assign函数十分一致,就不再重复了,请读者自行试验。

程序示例: // appending to string #include #include using namespace std; int main () { string str; string str2=\"Writing \"; string str3=\"print 10 and then 5 more\"; // used in the same order as described above: str.append(str2); // \"Writing \" str.append(str3,6,3); // \"10 \" str.append(\"dots are cool\ str.append(\"here: \"); // \"here: \" str.append(10,'.'); // \"..........\" str.append(str3.begin()+8,str3.end()); // \" and then 5 more\" str.append(5,0x2E); // \".....\" cout << str << endl; return 0; } 13

BSOI

输出: Writing 10 dots here: .......... and then 5 more.....

insert函数

string& insert ( size_t pos1, const string& str );

string& insert ( size_t pos1, const string& str, size_t pos2, size_t n ); string& insert ( size_t pos1, const char* s, size_t n); string& insert ( size_t pos1, const char* s ); string& insert ( size_t pos1, size_t n, char c ); 向字符串中插入内容。

插入的位置从pos1开始,后续参数与append函数一致,不再冗述

程序示例:

// inserting into a string #include #include using namespace std; int main () { string str=\"to be question\"; string str2=\"the \"; string str3=\"or not to be\"; string::iterator it; //迭代器,我也搞不懂是什么,暂时跳过吧――译者。 // used in the same order as described above: str.insert(6,str2); // to be (the )question str.insert(6,str3,3,4); // to be (not )the question str.insert(10,\"that is cool\ str.insert(10,\"to be \"); // to be not (to be )that is the question str.insert(15,1,':'); // to be not to be(:) that is the question it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...) str.insert (it+2,str3.begin(),str3.begin()+3); // (or ) cout << str << endl; return 0; } 14 BSOI

输出: to be, or not to be: that is the question...

erase函数

string& erase ( size_t pos = 0, size_t n = npos );

从字符串中清除内容,减小字符串长度。 参数:pos:清除字符串的起点位置。

n:清除的字符数量。

程序示例:

// string::erase #include #include using namespace std; int main () { string str (\"This is an example phrase.\"); str.erase (10,8); 输出: This is an phrase.

cout << str << endl; // \"This is an phrase.\" } replace函数

string& replace ( size_t pos1, size_t n1, const string& str );

string& replace ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 );

string& replace ( size_t pos1, size_t n1, const char* s, size_t n2 ); string& replace ( size_t pos1, size_t n1, const char* s ); string& replace ( size_t pos1, size_t n1, size_t n2, char c );

根据传递的参数,替换当前字符串中的一部分。

string& replace ( size_t pos1, size_t n1, const string& str );

15

BSOI

当前字符串内容,从pos1起始,长度为n1的部分,被str替换。

string& replace ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 );

当前字符串内容从pos1起始,长度为n1的部分,被str中以pos2起始,长度为n2的子串替换。

string& replace ( size_t pos1, size_t n1, const char* s, size_t n2 );

当前字符串内容从pos1起始,长度为n1的部分,被s指向的以null结束的字符序列(C字符串)替换,如果s指向的字符序列长度大于n2,则替换前n2个字符。 string& replace ( size_t pos1, size_t n1, const char* s );

当前字符串内容从pos1起始,长度为n1的部分,被s指向的以null结束的字符序列(C字符串)替换,字符序列的长度由第一个null标记决定。

string& replace ( size_t pos1, size_t n1, size_t n2, char c );

当前字符串内容从pos1起始,长度为n1的部分,被c填充n2次。

程序示例:

// replacing in a string #include #include using namespace std; int main () { string base=\"this is a test string.\"; string str2=\"n example\"; string str3=\"sample phrase\"; string str4=\"useful.\"; // function versions used in the same order as described above: // Using positions: 01234567*1234567*12345 string str=base; // \"this is a test string.\" str.replace(9,5,str2); // \"this is an example string.\" str.replace(19,6,str3,7,6); // \"this is an example phrase.\" str.replace(8,10,\"just all\ str.replace(8,6,\"a short\"); // \"this is a short phrase.\" str.replace(22,1,3,'!'); // \"this is a short phrase!!!\" cout<16

BSOI

swap函数

void swap ( string& str );

交换两个字符串的内容。调用此成员函数后,str中的内容就变成了string中的内容,反之亦然。

注意 ,存在一个同名的、且执行相同操作的全局函数(不是string的成员函数)swap。 该函数的形式是:

void swap ( string& lhs, string& rhs);

执行时,该函数实际调用(完全等价于):

lhs.swap(rhs);

程序示例: #include #include using namespace std; main () { string buyer (\"money\"); string seller (\"goods\"); cout << \"Before swap, buyer has \" << buyer; cout << \" and seller has \" << seller << endl; swap (buyer,seller); cout << \" After swap, buyer has \" << buyer; cout << \" and seller has \" << seller << endl; return 0; } 输出: Before swap, buyer has money and seller has goods After swap, buyer has goods and seller has money find函数

size_t find ( const string& str, size_t pos = 0 ) const; size_t find ( const char* s, size_t pos, size_t n ) const; size_t find ( const char* s, size_t pos = 0 ) const; size_t find ( char c, size_t pos = 0 ) const;

在当前字符串中寻找str、s、或c指定的内容,并返回其首次出现的位置。 如果指定了pos,则只在pos之后的字符中查找,忽略前面可能出现的内容。

参数:str:在当前字符串中查找的字符串,只有str的全部内容在当前字符串中被找到,才被认为是匹配的。

参数:s:一个字符序列。在函数的第二种形式中,匹配的内容长度取决于参数n。而在第三种形式中,s是一个以null结束的字符序列(C字符串),它的长度取决于第一个null标志出现的位置,只有null前的全部内容在当前字符串中被找到,才被认为是匹配的。 n:被查找序列的长度(见上)。 c:被查找的单独字符。

17

BSOI

pos:当前字符串中pos以后的数据将被用来搜索,如果指定为0则搜索整个字符串。 返回值:返回被查找内容首次出现的位置,如果查找失败,返回-1;

程序示例:

#include #include using namespace std; int main () { string str (\"There are two needles in this haystack with needles.\"); string str2 (\"needle\"); size_t found; found=str.find(str2); if (found!=string::npos) cout << \"first 'needle' found at: \" << int(found) << endl; found=str.find(\"needles are small\ if (found!=string::npos) cout << \"second 'needle' found at: \" << int(found) << endl; found=str.find(\"haystack\"); if (found!=string::npos) cout << \"'haystack' also found at: \" << int(found) << endl; found=str.find('.'); if (found!=string::npos) cout << \"Period found at: \" << int(found) << endl; // let's replace the first needle: str.replace(str.find(str2),str2.length(),\"preposition\"); cout << str << endl; return 0; }

输出:

first 'needle' found at: 14 second 'needle' found at: 44 'haystack' also found at: 30 Period found at: 51 There are two prepositions in this haystack with needles.

rfind函数

size_t rfind ( const string& str, size_t pos = npos ) const; size_t rfind ( const char* s, size_t pos, size_t n ) const; size_t rfind ( const char* s, size_t pos = npos ) const; size_t rfind ( char c, size_t pos = npos ) const;

从右向左查找字符(串),参见find函数。 常数npos = -1。

18

BSOI

substr函数

string substr ( size_t pos = 0, size_t n = npos ) const;

生成子串。

返回一个内容已被初始化为当前字符串子串的新字符串。子串中的字符序列从原串pos位置开始,长度为n个字符。

参数:pos:当前字符串中要生成子串的起始位置,如果这个位置超过了字符串结束位置,会产生一个out_of_range例外错误。

n:子串长度。如果这个值会使生成的子串超过原串的内容的结束位置,则只有原串范围内的字符生效。npos是一个size_t类型的n参数最大可取到的值,如果应用这个值,则子串会包括原串pos后的全部内容。

程序示例: // string::substr #include #include using namespace std; int main () { string str=\"We think in generalities, but we live in details.\"; // quoting Alfred N. Whitehead string str2, str3; size_t pos; str2 = str.substr (12,12); // \"generalities\" pos = str.find(\"live\"); // position of \"live\" in str str3 = str.substr (pos); // get from \"live\" to the end cout << str2 << ' ' << str3 << endl; return 0; } 输出: generalities live in details.

比较字符串大小

直接用“>”、“<=”、“<”、“>=”即可,请自行实验。

19

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 69lv.com 版权所有 湘ICP备2023021910号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务