8.11.2 连接字符串(1)
字符串最常见的运算可能是连接两个字符串形成一个新的字符串了。可以用+运算符连接两个字符串对象或者一个字符串对象和一个字符串字面值。下面是一些示例:
- string sentence1("This sentence is false.");
- string sentence2("Therefore the sentence above must be true!");
- string combined; // Create an empty string
- sentence1sentence1 = sentence1 + "\n"; // Append string containing newline
- combined = sentence1 + sentence2; // Join two strings
- cout << combined << endl; // Output the result
执行这些语句将得到下面的输出:
- This sentence is false.
- Therefore the sentence above must be true!
前3个语句创建字符串对象。下一个语句将字符串字面值"\n"附加到sentence1后面,并将结果存储在sentence1中。再下一个语句连接sentence1和sentence2,并将结果存储在combined中。最后一个语句输出字符串combined。
字符串可以用+运算符连接,是因为string类实现了operator+()。这意味着操作数之一必须为string对象,因此不能用+运算符连接两个字符串字面值。记住,每次用+运算符连接两个字符串时,都是在创建一个新的string对象,这会带来一定的开销。下一节将介绍如何修改和扩展现有的string对象,在有些情况下这可能是一种更有效的方法,因为它不涉及创建新对象。
也可以用+运算符将一个字符连接到一个字符串对象上,因此前面代码片段中的第4个语句可以写成:
- sentence1sentence1 = sentence1 + '\n'; // Append newline character to string
string类也可以实现operator+=(),因此右操作数可以是一个字符串字面值、一个字符串对象或者一个字符。前面的语句可以写成:
- sentence1 += '\n';
或者写成:
- sentence1 += "\n";
使用+=运算符与使用+运算符有一个区别。如前所述,+运算符创建一个包含合并后的字符串的新字符串对象。+=运算符将作为右操作数的字符串或字符附加到作为左操作数的string对象后面,因此直接修改string 对象,而不创建新的对象。
下面用一个示例来练习上面描述的概念。
试一试:创建与连接字符串
这一简单示例通过键盘输入姓名和年龄,然后列出输入的内容。代码如下:
- // Ex8_13.cpp
- // Creating and joining string objects
- #include <iostream>
- #include <string>
- using std::cin;
- using std::cout;
- using std::endl;
- using std::string;
- using std::getline;
- // List names and ages
- void listnames(string names[], string ages[], size_t count)
- {
- cout << endl << "The names you entered are: " << endl;
- for(size_t i = 0 ; i < count && !names[i].empty() ; ++i)
- cout << names[i] + " aged " + ages[i] + '.' << endl;
- }
- int main()
- {
- const size_t count = 100;
- string names[count];
- string ages[count];
- string firstname;
- string secondname;
- for(size_t i = 0 ; i < count ; i++)
- {
- cout << endl << "Enter a first name or press Enter to end: ";
- getline(cin, firstname, '\n');
- if(firstname.empty())
- {
- listnames(names, ages, i);
- cout << "Done!!" << endl;
- return 0;
- }
- cout << "Enter a second name: ";
- getline(cin, secondname, '\n');
- names[i] = firstname + ' ' + secondname;
- cout << "Enter " + firstname + "'s age: ";
- getline(cin, ages[i], '\n');
- }
- cout << "No space for more names." << endl;
- listnames(names, ages, count);
- return 0;
- }