吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 在 C/C++ 中反转字符串的不同方法

在 C/C++ 中反转字符串的不同方法

来源:网络 | 更新时间:2022-01-13 20:36:57
给定一个字符串,编写一个 C/C++ 程序来反转它。
  • 通过交换字符编写自己的反向函数:一个简单的解决方案是编写我们自己的反向函数来反转C++ 中的字符串。
// A Simple C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;

// Function to reverse a string
void reverseStr(string& str)
{
int n = str.length();

// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}

// Driver program
int main()
{
string str = "52cxydh";
reverseStr(str);
cout << str;
return 0;
}
输出
hdyxc25
  • 使用内置的“reverse”函数: “algorithm”头文件中有一个直接函数可以进行反向操作,节省了我们编程的时间。 
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin, BidirectionalIterator end);
// A quickly written program for reversing a string
// using reverse()
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "52cxydh";

// Reverse str[begin..end]
reverse(str.begin(), str.end());

cout << str;
return 0;
}
输出
hdyxc25
  • 只打印反向
// C++ program to print reverse of a string
#include <bits/stdc++.h>
using namespace std;

// Function to reverse a string
void reverse(string str)
{
for (int i=str.length()-1; i>=0; i--)
cout << str[i];
}

// Driver code
int main(void)
{
string s = "52cxydh";
reverse(s);
return (0);
}
输出
hdyxc25
  • 获取 const 字符串的反转: 
// C++ program to get reverse of a const string
#include <bits/stdc++.h>
using namespace std;

// Function to reverse string and return
// reverse string pointer of that
char* reverseConstString(char const* str)
{
// find length of string
int n = strlen(str);

// create a dynamic pointer char array
char *rev = new char[n+1];

// copy of string to ptr array
strcpy(rev, str);

// Swap character starting from two
// corners
for (int i=0, j=n-1; i<j; i++,j--)
swap(rev[i], rev[j]); 

// return pointer of the reversed string
return rev;
}

// Driver code
int main(void)
{
const char *s = "52cxydh";
printf("%s", reverseConstString(s));
return (0);
}
输出
hdyxc25
  • 使用构造函数反转字符串:将反向迭代器传递给构造函数会返回一个反转字符串。
// A simple C++ program to reverse string using constructor
#include <bits/stdc++.h>
using namespace std;
int main(){

string str = "52cxydh";

//Use of reverse iterators
string rev = string(str.rbegin(),str.rend());

cout<<rev<<endl;
return 0;
}
输出
hdyxc25
  •  使用临时字符串
// A simple C++ program to reverse string using constructor
#include <bits/stdc++.h>
using namespace std;
int main(){

string str = "52cxydh";
int n=str.length();
//Temporary string to store the reverse
string rev;
for(int i=n-1;i>=0;i--)
rev.push_back(str[i]);

cout<<rev<<endl;
return 0;
}
输出 hdyxc25    

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com