C++ 字符串


2022年9月4日, Learn eTutorial
2495

在本教程中,您将学习如何在 C++ 中处理字符串。您将学习如何声明、初始化以及在各种输入/输出活动中使用它们。除此之外,我们还将了解 C++ 字符串的含义、C++ 中的 C 风格字符字符串以及 C++ 字符串与字符数组之间的主要区别。

C++ 是一种广泛使用的通用编程语言,它在一定程度上使用了面向对象编程(OOPs)原则。通过 C++ 字符串,它允许您处理文本和字符。本教程涵盖了所有关于 String 类的信息。

字符串就是一组/集合字符。C++ 编程语言通常使用两种类型的字符串

  • 字符串类的对象
  • C 字符串(C 风格字符串)
     

C++ 字符串到底是什么?

C++ 字符串用于文本和字符的表示和操作。有两种不同的字符串表示形式:C 风格字符字符串和主要在 C++ 中引入的 String 类。

C++ strings

C 风格字符字符串

C 风格字符字符串是 C 编程语言的一个特性,现在在 C++ 中也可用。它类似于一维字符数组,包含一个字符序列,并以空字符结尾。因此,如果您想保留单词“Hello”,您可以创建一个 C 风格字符字符串,其中包含字符“H”、“e”、“l”、“l”、“o”和“0”。

在这种情况下,您所要做的就是告诉编译器将单词“Hello”保存为字符串。但默认情况下,它仍然会在末尾包含字符“\0”。请看以下示例,它演示了如何使用字符数组主要在一个变量中构建和存储 C 风格字符字符串。


#include 

using namespace std;

int main (){

   char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "This is a wonderful greeting message for you: ";

   cout << greet << endl;

   return 0;

}

 

输出


This is a wonderful greeting message for you: Hello

如何定义 C 风格字符串?


char str[] = "C++";
 

以上代码中的字符串 str 包含 4 个字符。

尽管“C++”有三个字符,但空字符 \0 会自动附加到给定字符串的末尾。

这些是定义字符串的不同方法


char str[4] = "C++";
     
char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};
 

C++ String 类是如何在 C++ 中引入的?

OOP 概念是 C++ 的基础,它允许您将字符串表示为 String 类的对象 (std::string)。该类允许您快速声明字符串变量,并且还可以帮助存储其中的任何字符序列。这里有一个示例,说明如何使用 String 类来表示字符串。


#include <iostream>

using namespace std;

int main(){

    string greet = "Hello beautiful";

    cout << "This is a wonderful greeting message only for you: ";

    cout<<greet<<endl;

}

输出


This is a wonderful greeting message only for you: Hello beautiful

如上图所示,无需声明一个数组来保存字符。

C++ 字符串与字符数组有什么区别?

尽管 C 风格字符字符串和 C++ String 类都用于表示字符串,但它们之间存在一些区别。最显着的区别是

  • 字符串是定义对象的类,而字符数组是数组。
  • 字符数组的大小是静态预分配的。因此,在运行时无法访问更多内存,并且未使用的内存被浪费。字符串大小不是预分配的,因此没有浪费,并且在运行时可以访问更多内存。
  • 字符串不会发生数组衰减,而字符数组会。
  • 在实现方面,字符串比字符数组花费的时间更长。
  • String 类提供了更多内置函数来与字符串交互和操作字符串。

C++ 字符串中的输入函数

输入函数可用于向字符串添加或删除字符或字符串。输入函数包括:

  • getline():主要用于读取和存储用户通过输入流输入的字符串
  • push_back():在字符串末尾添加一个新字符。
  • pop_back():从字符串中弹出或删除最后一个字符。

示例:让我们主要使用 C++ 输入函数编写一个程序


#include<iostream>

#include<string>

using namespace std;

int main(){

// here declaring of a string variable is done

string s;

    cout << " Please enter a string: ";   

// Using getline() in order to accept input


getline(cin,s);

// For displaying the entered string

cout << "Our initial string will be : ";

cout << s << endl;

// just Insert a character i at the end of the string

//now we will be  using the push_back function

s.push_back('i');

// Displaying the string just after push_back

cout << "The new string is : ";

cout << s << endl;

// Deleting the i from the end using pop_back which we inserted

s.pop_back();

// Displaying the string after pop_back

cout << "After pop_back operation, our string will be : ";

cout << s << endl;

return 0;

}

输出

Please enter a string: Welcome to learn eTutorials
Our initial string will be : Welcome to learn eTutorials
The new string is : Welcome to learn eTutorialsi
After pop_back operation, our string will be : Welcome to learn eTutorials

C++ 中的字符串迭代器函数

顾名思义,迭代器函数用于与遍历字符串中每个字符的迭代器交互。

  • begin():将迭代器带回开头。
  • end():它将迭代器返回到末尾
  • rbegin():它将始终返回一个指向末尾的反向迭代器
  • rend():它将始终返回一个指向开头的反向迭代器

示例:让我们使用字符串类迭代器函数编写一个程序


#include<iostream>

#include<string>

using namespace std;

int main(){

string s = "LearneTutorials";

// Declaring the iterator

std::string::iterator iter;

// Declaring the iterator mainly for reverse functions

std::string::reverse_iterator iter1;

// Displaying the string

cout << " We are using the forward iterators : ";

for (iter=s.begin(); iter!=s.end(); iter++)

cout << *iter;

cout << endl;

// Displaying the reverse string

cout << "Now we are using the reverse iterators : ";

for (iter1=s.rbegin(); iter1!=s.rend(); iter1++)

cout << *iter1;

cout << endl;

return 0;

}

输出

We are using the forward iterators : LearneTutorials
Now we are using the reverse iterators : slairotuTenraeL

为了遍历字符串,在这种情况下,我们在代码中使用了 for 循环以及正向和反向迭代器。使用正向迭代器的第一个 for 循环继续遍历和打印字符,直到到达字符串的末尾。然后,我们在第二个 for 循环中使用了反向迭代器,从末尾开始遍历并打印字符,一直到字符串的开头。

C++ 中的字符串容量函数

C++ 字符串容量函数使处理字符串的大小和容量变得更容易。以下是容量类型的主要用途

  • capacity():返回编译器为字符串分配的空间量。
  • resize():这允许您增加或减少字符串的长度/大小。
  • length():返回字符串的大小。
  • shrink_to_fit():减少容量并使其相等以节省内存。

示例:现在让我们使用字符串类容量函数编写一个 C++ 程序


#include<iostream>

#include<string>

using namespace std;

int main(){

string s = "C++ Programming is very much interesting!";

cout << "Initial string : ";

cout << s << endl;

// Resizing string using resize()

s.resize(15);

cout << "String after  resizing is done : ";

cout << s << endl;

// Using the capacity function

cout << "String's capacity is : ";

cout << s.capacity() << endl;

// Using the length function

cout<<"String's length will be : "<<s.length()<<endl;

// Using the shrink_to_fit function

s.shrink_to_fit();

cout << "Capacity of the post shrinking is : ";

cout << s.capacity() << endl;

return 0;

}

输出

Initial string : C++ Programming is very much interesting!
String after  resizing is done : C++ Programming
String's capacity is : 41
String's length will be : 15
Capacity of the post shrinking is : 15

C++ 中的字符串操作函数

通过使用复制和交换等操作,您可以使用操作函数来操作字符串。

  • copy():它复制 char 数组子字符串的一部分。复制子字符串的长度和起始位置分别由参数 lenpos 指定。
  • swap():它将一个字符串与另一个字符串交换。

示例:现在让我们使用字符串操作函数编写一个 C++ 程序


#include<iostream>

#include<string>

using namespace std;

int main(){

string s1 = "Welcome All, let us enjoy  learning C++ with learn eTutorials";

string s2 = "C++ is Awesome!";

// Declaring character array

char ch_arr[80];

// Using copy() to copy elements from s1 and

// placing it in ch_arr

s1.copy(ch_arr,40,10);

// Printing of the array

cout << "Character array : ";

cout << ch_arr << endl << endl;

//  before swapping the strings

cout << " The String number 1 just before swapping is : ";

cout << s1 << endl;

cout << "The String number 2  just before swapping is : ";

cout << s2 << endl;

// using swap() function

s1.swap(s2);

// Strings after swapping

cout << "String number 1  after swapping will be : ";

cout << s1 << endl;

cout << "String number 2 after swapping will be : ";

cout << s2 << endl;

return 0;

}

输出

Character array : l, let us enjoy  learning C++ with learn

The String number 1 just before swapping is : Welcome All, let us enjoy  learning C++ with learn eTutorials
The String number 2  just before swapping is : C++ is Awesome!
String number 1  after swapping will be : C++ is Awesome!
String number 2 after swapping will be : Welcome All, let us enjoy  learning C++ with learn eTutorials