反向显示字符串

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在这个实验中,你将学习如何编写一个 C++ 程序来反向显示给定的字符串。在 C++ 中,有多种方法可以反转给定的字符串。我们将探索两种不同的方法:使用我们自己构建的自定义反转函数,以及使用 C++ 内置的 reverse 函数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/StandardLibraryGroup -.-> cpp/string_manipulation("`String Manipulation`") cpp/StandardLibraryGroup -.-> cpp/standard_containers("`Standard Containers`") subgraph Lab Skills cpp/strings -.-> lab-96184{{"`反向显示字符串`"}} cpp/for_loop -.-> lab-96184{{"`反向显示字符串`"}} cpp/function_parameters -.-> lab-96184{{"`反向显示字符串`"}} cpp/output -.-> lab-96184{{"`反向显示字符串`"}} cpp/string_manipulation -.-> lab-96184{{"`反向显示字符串`"}} cpp/standard_containers -.-> lab-96184{{"`反向显示字符串`"}} end

自定义函数反转字符串

首先,让我们编写一个自定义函数来反转给定的字符串。该函数会将第一个字符与最后一个字符交换,然后将第二个字符与倒数第二个字符交换,依此类推,直到整个字符串被反转。

创建 reverseStr 函数并通过引用传递字符串。这样,我们可以修改原始字符串,而不是返回一个新的字符串。该函数将包含一个 for 循环,用于交换字符串两侧的字符,逐步向内移动,直到整个字符串被反转。

#include<iostream>
#include<string>
using namespace std;

void reverseStr(string& str) {
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        swap(str[i], str[n - i - 1]);
    }
}

使用内置的 "reverse" 函数

C++ 还提供了一个内置函数来反转字符串,该函数位于 <algorithm> 头文件中。我们可以通过传递要反转字符串的起始和结束位置来使用 reverse() 函数。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main() {
    string str = "hello";
    reverse(str.begin(), str.end());
    cout << str;
    return 0;
}

测试程序

让我们使用上述任意一种方法来测试程序。为此,只需调用你刚刚创建的函数或内置的 reverse() 函数。将要反转的字符串作为参数传递给函数。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

void reverseStr(string& str) {
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        swap(str[i], str[n - i - 1]);
    }
}

int main() {
    string myString = "Hello World!"; //定义一个要反转的字符串

    //方法 1
    cout << "使用自定义函数反转字符串:\n";
    reverseStr(myString); //调用自定义函数反转字符串
    cout << myString << endl;

    //方法 2
    cout << "\n使用内置 'reverse' 函数反转字符串:\n";
    reverse(myString.begin(), myString.end()); //调用内置函数反转字符串
    cout << myString << endl;

    return 0;
}

总结

在这个实验中,我们学习了如何编写一个 C++ 程序来反向显示给定的字符串。我们探索了两种不同的方法:使用我们自己创建的自定义函数,以及使用 C++ 内置的 reverse 函数。我们还通过调用函数测试了这两种方法的程序。现在,你可以快速反转任何字符串了!

您可能感兴趣的其他 C++ 教程