C++ string

来源:互联网 发布:网页数据抓取软件 编辑:程序博客网 时间:2024/06/04 23:20

string

 C-style strings have a special feature: 每个字符串的最后一个字符是空字符. This character, written \0, is the character with ASCII code 0, and it serves to mark the string's end. For example, consider the following two declarations:


char dog[8] = { 'b', 'e', 'a', 'u', 'x', ' ', 'I', 'I'};      // not a string!
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'};       // a string!


上面两个数组都是字符数组,但只有第二个是字符串。The null character plays a fundamental role in C-style strings. For example, C++ has many functions that handle strings, including those used by cout. They all work by processing a string character-by-character until they reach the null character.


char bird[11] = "Mr. Cheeps"; // the \0 is understood
char fish[] = "Bubbles"; // let the compiler count


iterators

begin (cbegin)         返回an iterator to the beginning

end (cend)              返回 an iterator to the end 

rbegin (crbegin)      返回a reverse iterator to the beginning

rend (crend)            返回 a reverse iterator to the end 


capacity

empty()               checks whether the string is empty 

size (length)            returns the number of characters

 max_size()             returns the maximum number of characters

capacity                  返回当前存储空间所能存储的最大字符数


一些操作函数







Quoted strings(引用字符串) always include the terminating null character implicitly.
Of course, you should make sure the array is large enough to hold all the characters of the string, including the null character.(字符串的长度要足够长,要包括空字符)
functions that work with strings are guided by the location of the null character, not by the size of the array.


Note that a string constant (with double quotes) is not interchangeable(可替换)with a character constant (with single quotes). A character constant, such as 'S', is a shorthand notation for the code for a character. On an ASCII system, 'S' is just another way of writing 83. Thus, the following statement assigns the value 83 to shirt_size: 


char shirt_size = 'S'; // this is fine


But "S" is not a character constant; it represents the string consisting of two characters, the S and the \0 characters. Even worse, "S" actually represents the memory address at which the string is stored. So a statement like the following attempts to assign a memory address to shirt_size:


char shirt_size = "S"; // illegal type mismatch


Concatenating String Literals
Indeed, any two string constants separated only by whitespace (spaces, tabs, and newlines) are automatically joined into one.Thus, all the following output statements are equivalent to each other:


cout << "I'd give my right arm to be" " a great violinist.\n";
cout << "I'd give my right arm to be a great violinist.\n";
cout << "I'd give my right ar"
"m to be a great violinist.\n";


Note that the join doesnt add any spaces to the joined strings.The first character of the second string immediately follows the last character, not counting \0, of the first string.The \0 character from the first string is replaced by the first character of the second string.第一个字符串的\0字符会被第二个字符串的首个字符所代替。


Reading String Input a Line at a Time
To be able to enter whole phrases instead of single words as a string, you need a different approach to string input. Specifically, you need a line-oriented method instead of a word-oriented method.You are in luck, for the istream class, of which cin is an example, has some line-oriented class member functions: getline() and get(). Both read an entire input line—that is, up until a newline character. However, getline() then discards the newline character, whereas get() leaves it in the input queue. Let’s look at the details, beginning with getline().


getline(): 
The getline() function reads a whole line, using the newline character transmitted by the Enter key to mark the end of input.You invoke this method by using cin.getline() as a function call.
The getline() member function stops reading input when it reaches this numeric limit or when it reads a newline character, whichever comes first.
For example, suppose you want to use getline() to read a name into the 20-element name array.You would use this call:


cin.getline(name,20);


This reads the entire line into the name array, provided that the line consists of 19 or fewer characters. 


Line-Oriented Input with get()
The istream class has another member function, get( ), which comes in several variations. One variant works much like getline( ). It takes the same arguments, interprets them the same way, and reads to the end of a line. But rather than read and discard the newline character, get( ) leaves that character in the input queue. Suppose you use two calls to get( ) in a row:
(get( )会将前面读到的数据存在缓存队列中)


cin.get(name, ArSize);
cin.get(dessert, Arsize); // a problem不会有这行的输入过程,直接跳过


因为第一次调用get( )将输入的newline character留在输入序列中,newline character是第二次调用get( )得到的第一个字符。因此,get( )认为它已经到了line的尾部,而不需要读入任何数据,没有帮助的话,get( )就跨不过已经读入的newline character.


The call cin.get( ) (with no arguments) reads the single next character, even if it is a newline, so you can use it to dispose of the newline character and prepare for the next line of input.That is, this sequence works:


cin.get(name, ArSize);       // read first line
cin.get(); // read newline
cin.get(dessert, Arsize);     // read second line


Another way to use get() is to concatenate, or join, the two class member functions, as
follows:


cin.get(name, ArSize).get(); // concatenate member functions


What makes this possible is that cin.get(name, ArSize) returns the cin object, which is then used as the object that invokes the get( ) function. 


Similarly, the following statement reads two consecutive input lines into the arrays name1 and name2; its equivalent to making two separate calls to cin.getline( ):


cin.getline(name1, ArSize).getline(name2, ArSize);


Mixing String and Numeric Input


int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
输出:
What year was your house built?
1966
What is its street address?
Year built: 1966
Address
Done!
在这段程序中,没有输入地址的机会,问题是当cin读取year时,它会将Enter key生成的newline保存在input queue中。然后cin.getline( )会将读取到的newline视为an empty line,然后将一个null string放到address数组中。解决方法是在读取address数组前read and discard the new line。可以用带argument或不带argument的get( )来解决。


cin >> year;
cin.get();        // or cin.get(ch);


或者concatenate the calls:


(cin >> year).get();      // or (cin >> year).get(ch);


More string Class Operations
The cstring header file (formerly string.h) supports these functions. For example, you can use the strcpy( ) function to copy a string to a character array, and you can use the strcat( ) function to append a string to a character array:


strcpy(charr1, charr2);        // copy charr2 to charr1
strcat(charr1, charr2);         // append contents of charr2 to char1将charr2连接到charr1的末尾


int len1 = str1.size();              // obtain length of str1
int len2 = strlen(charr1);       // obtain length of charr1


The strlen( ) function is a regular function that takes a C-style string as its argument and that returns the number of characters in the string.The size() function basically does the same thing, but the syntax for it is different.
原创粉丝点击