Cplusplus 简明教程
C++ Strings
C++ 提供以下两种类型字符串表示形式:
C++ provides following two types of string representations −
-
The C-style character string.
-
The string class type introduced with Standard C++.
The C-Style Character String
C 语言风格字符字符串起源于 C 语言,并且在 C++ 中继续得到支持。此字符串实际上是一个字符一维数组,一个 null 字符 '\0' 终止该数组。因此,一个以 null 结尾的字符串包含组成该字符串的字符和 null 字符。
The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
以下声明和初始化创建一个由单词 "Hello" 构成的字符串。为了在数组末尾保留一个空字符,包含字符串的字符数组的大小比单词 "Hello" 中的字符数量多一个。
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
如果你遵循数组初始化规则,则可以将上述语句写成如下形式:
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
以下是上面用 C/C++ 中定义的字符串的内存表述 −
Following is the memory presentation of above defined string in C/C++ −
实际上,无需在字符串常量的结尾处放置空字符。C++ 编译器将在初始化数组时自动在字符串结尾处放置 '\0'。我们可以尝试打印上面提到的字符串 −
Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −
Example
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C Style String Functions
C++ 支持大量操作空终止字符串的函数。这些函数在 <string.h> header file 中定义。
C++ supports a wide range of functions that manipulate null-terminated strings. These functions are defined in <string.h> header file.
Sr.No |
Function & Purpose |
1 |
strcpy(s1, s2); Copies string s2 into string s1. |
2 |
strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3 |
strlen(s1); Returns the length of string s1. |
4 |
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 |
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. |
6 |
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. |
Example
下面的示例使用了上面提到的几个函数 −
Following example makes use of few of the above-mentioned functions −
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}
当上述代码被编译并执行时,它会产生类似以下结果 −
When the above code is compiled and executed, it produces result something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
The String Class in C++
标准 C++ 函数库提供了一个 string 类类型,支持上面提到的所有操作,另外还提供了更多功能。
The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality.
Example of String Class
让我们查看以下示例 −
Let us check the following example −
#include <iostream>
#include <string>
using namespace std;
int main () {
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total length of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
当上述代码被编译并执行时,它会产生类似以下结果 −
When the above code is compiled and executed, it produces result something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
Creating a String
我们可以使用以下方法之一创建字符串变量,以下两种方法任选 −
We can create string variables in two ways, using either of the following methods −
Creating String Using Character Arrays
我们可以使用 C-type arrays 以字符的格式声明字符串。此做法使用以下语法 −
We can declare strings using the C-type arrays in the format of characters. This is done using the following syntax −
char variable_name[len_value] ;
此处,len_value 是字符数组的长度。
Here, len_value is the length of the character array.
在以下示例中,我们声明了一个字符数组,并为其赋值。
In the following examples, we are declaring a character array, and assigning values to it.
#include <iostream>
using namespace std;
int main() {
char s[5]={'h','e','l','l','o'};
cout<<s<<endl;
return 0;
}
hello
Creating String using <string>
我们可以使用 'string' 关键字声明字符串变量。这包含在 <string> header file 中。声明字符串的语法如下文所述 −
We can declare a String variable using the 'string' keyword. This is included in the <string> header file. The syntax of declaring a string is explained as follows −
string variable_name = [value];
这里,[value] 是可选的,可在声明期间用于赋值。
Here, [value] is an optional and can be used to assign value during the declaration.
在以下示例中,我们声明了一个字符串变量,并为其赋值。
In the following examples, we are declaring a string variable, assigning a value to it.
#include <iostream>
using namespace std;
int main() {
string s="a merry tale";
cout<<s;
return 0;
}
a merry tale
Traversing a String (Iterate Over a String)
我们可以通过两种方式迭代字符串 −
We can iterate over a string in two ways −
Using looping statements
我们可以使用for循环、while循环和do while循环遍历字符串,方法是使用指向字符串第一个和最后一个索引的指针。
We can traverse a string using for loops, while loops and do while loops using a pointer to the first and the last index in the string.
Using iterators
使用基于范围的循环,我们可以使用迭代器来遍历字符串。这是通过在运行基于范围的循环时使用“:”运算符来实现的。
Using range based loops, we can iterate over the string using iterators. This is achieved using ":" operator while running a range based loop.
Example of Iterating a String
以下示例代码显示了使用这两种方法进行字符串遍历的方法:
The following example code shows string traversal using both of these methods −
#include <iostream>
using namespace std;
int main() {
string s="Hey, I am at TP.";
for(int i=0;i<s.length();i++){
cout<<s[i]<<" ";
}
cout<<endl;
for(char c:s){
cout<<c<<" ";
}
return 0;
}
H e y , I a m a t T P .
H e y , I a m a t T P .
Accessing Characters of String
我们可以使用迭代器和指向字符串索引的指针来访问字符串的字符。
We can access the characters of a string using both iterators and pointer to the indices of the string.
Example
以下示例代码显示了我们如何访问字符串中的字符:
The following example code shows how we can access the characters in a string −
#include <iostream>
using namespace std;
int main() {
string s="Hey, I am at TP.";
cout<<s<<endl;
for(int i=0;i<s.length();i++){
s[i]='A';
}
cout<<s<<endl;
for(char &c:s){
c='B';
}
cout<<s<<endl;
return 0;
}
Hey, I am at TP.
AAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBB
String Functions
String 是`string`类的对象,因此它具有各种函数,用户可以使用这些函数进行各种操作。其中一些功能如下:
String is an object of the <string> class, and hence, it has a variety of functions that users can utilize for a variety of operations. Some of these functions are as follows −
Function |
Description |
This function returns the length of the string. |
|
This function is used to swap the values of 2 strings. |
|
Used to find the size of string |
|
This function is used to resize the length of the string up to the given number of characters. |
|
Used to find the string which is passed in parameters |
|
This function is used to push the character at the end of the string |
|
This function is used to pop the last character from the string |
|
This function is used to remove all the elements of the string. |
|
This function is used to search for a certain substring inside a string and returns the position of the first character of the substring. |
|
This function is used to replace each element in the range [first, last) that is equal to old value with new value. |
|
This function is used to create a substring from a given string. |
|
This function is used to compare two strings and returns the result in the form of an integer. |
|
This function is used to remove a certain part of a string. |
Length of a String
字串的长度就是字串中出现字符的数量。因此,“apple”这个字串的长度是 5 个字符,“hello son”这个字串的长度是 9 个字符(包括空格)。这可以使用 <string> header file 中的长度()方法访问。
The length of a string is the number of characters present in the string. Hence, the string "apple" has a length of 5 characters and the string "hello son" has a length of 9 characters (including empty spaces). This can be accessed using the length() method in <string> header file.
String Concatenation
字符串连接是将两个字符串加在一起的一种方法。这可以使用两种方式完成 -
String concatenation is a way to add two strings together. This can be done using two ways −
Addition Operator
加法运算符用于添加两个元素。对于字符串,加法运算符连接两个字符串。在以下示例中对此进行了明确解释 -
The addition operator is used to add two elements. In case of strings, the addition operator concatenates the two strings. This is clearly explained in the following example −
#include <iostream>
#include <string>
using namespace std;
int main() {
string x = "10";
string y = "20";
cout<<x+y<<endl;
return 0;
}
1020
这与整数加法不同。当我们取两个整数并使用加法运算符将它们相加时,我们会得到这两个数字的和。
This is different from integer addition. When we take two integers and add them using addition operator, we get the sum of the two numbers instead.
在以下示例中对此进行了明确解释 -
This is clearly explained in the following example −
#include <iostream>
#include <string>
using namespace std;
int main() {
int x = 10;
int y = 20;
cout<<x+y<<endl;
return 0;
}
30
Using string append() method
C++ 是一种面向对象编程语言,因此字符串实际上是一个对象,其中包含可对字符串执行某些操作的函数。我们可以使用 string append() method 将一个字符串附加到另一个字符串。
C++ is an object oriented programming language, and hence a string is actually an object, which contain functions that can perform certain operations on strings. We can use string append() method to append one string to another.
此操作的语法如下 -
The syntax of this operation is as follows −
string_1.append(string_2);
此方法的使用在以下示例中进行了明确说明 -
The usage of this method is depicted clearly in the following example −
#include <iostream>
#include <string>
using namespace std;
int main() {
string x="hey boy";
string y=" now";
x.append(y);
cout<<x<<endl;
return 0;
}
hey boy now
String Input in C++
字符串可以作为程序的输入,最常见的方法是使用 cin 方法。
Strings can be taken as an input to the program, and the most common way to do this is by using cin method.
有三种方法可以将字符串作为输入,这些方法如下 -
There are three methods to take a string as an input, and these methods are given as follows −
-
cin
-
getline()
-
stringstream
Using cin Method
这是将字符串作为输入的最简单方法。语法如下 -
This is the simplest way to take a string as an input. The syntax is given as follows −
cin>>string_name;
#include <iostream>
using namespace std;
int main() {
string s;
cout << "Enter custom string : "<<endl;
//enter the string here
cin>>s;
cout<<"The string is : "<<s;
}
Using getline() Method
getline() 方法可用于从输入流中读取字符串。这在 <string> 头文件中定义。上述方法的语法如下 -
The getline() method can be used to read a string from an input stream. This is defined in the <string> header file. The syntax of the above method is given as follows −
getline(cin, string_name);
#include <iostream>
using namespace std;
int main() {
string s;
cout << "Enter String as input : " << endl;
getline(cin, s);
//enter the string here
cout << "Printed string is : " << s << endl;
return 0;
}
Using stringstream
字符串流类用于一次性接收多个字符串作为输入。上述方法的语法如下 -
The stringstream class is used to take multiple strings as input, all at once. The syntax of the above method is given as follows −
Stringstream object_name(string_name);
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "Hey, I am at TP";
stringstream object(s);
string newstr;
// >> operator will read from the stringstream object
while (object >> newstr) {
cout << newstr << " ";
}
return 0;
}
Hey, I am at TP