string Type

时间:2015-01-31 23:11:08   收藏:0   阅读:315

Notes from C++ Primer

 

Operations

Operations of string support lots of operations of sequential container.

As the operation of string is almost the same as container, many executions of vector can be replaced like codes below:

string s("Hiya!");
string::iterator iter = s.begin();
while(iter != s.end())
	cout << *iter++ << endl;	// postfix increment: print old value

 

 

Operations only for string

There‘re three base operations supported by string type but container type.

Operations of sub-string:

 

1. substr

We can pass the beginning position pos of ing substring and a counter n which determines the length of substring to function substr to finish returning substring.

string s("hello world");

// return substring of 5 characters starting at position 6
string s2 = s.substr(6, 5);		// s2 = world

An alternative way is:

// return substring from position 6 to the end of s
string s3 = s.substr(6);		// s3 = world

 

2. append and replace

append function offers an shortcut to insert string at the end of string:

string s("C++ Primer");		// initialize s to "C++ Primer"
s.append(" 3rd Ed.");		// s == "C++ Primer 3rd Ed."

// equivalent to s.append(" 3rd Ed.")
s.insert(s.size(), " 3rd ED.");

replace function is a shortcut of deleting some characters and then inserting other contents: 

// starting at position 11, erase 3 characters and then insert "4th"
s.replace(11, 3, "4th");	// s == "C++ Primer 4th Ed."

// equivalent way to replace "3rd" by "4th"
s.erase(11, 3);				// s == "C++ Primer Ed."
s.insert(11, "4th");		// s == "C++ Primer 4th Ed."

Also, we don‘t need to require the length of inserting string is the same as the length of deleting string. Thus we can replace longer or shorter string:

s.replace(11, 3, "Fourth");		// s == "C++ Primer Fourth Ed."

 

3. find operations of string

string class offers 6 kinds of serarch function. They all return a string::size_type type value indicating the position of match, or return a special value string::npos indicating fail. string class define npos as a value larger than any validate index of string.

The simple accurate search is find function.

string name("AnnaBelle");
string::size_type pos1 = name.find("Anna");		// pos1 == 0

By default, find operation is case sensitive:

string lowercase("annabelle");
pos1 = lowercase.find("Anna");		// pos1 == npos

 

原文:http://www.cnblogs.com/kid551/p/4264788.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!