编写这样的函数非常简单
std::string reverse( const std::string &s )
{
return { s.rbegin(),s.rend() };
}
这是一个演示程序
#include <iostream>
#include <string>
std::string reverse( const std::string &s )
{
return { s.rbegin(),s.rend() };
}
int main()
{
std::string s( "Hello World" );
std::cout << s << '\n';
std::cout << reverse( s ) << '\n';
return 0;
}
其输出为
Hello World
dlroW olleH
,
那么,您可以使用递归来做到这一点。如果您不知道什么是递归,则可以使用以下链接:link1和link2。
从技术上讲,这不会是循环。
string reverseString(string str,int index,string ans) {
if (index == -1) return ans;
ans += str[index];
return reverseString(str,index - 1,ans);
}
此函数的参数将是默认的str,即index = size(str)-1和ans ans =“”;
reverseString(str,size(str)-1,“”)。
如果您希望函数仅使用一个参数,则可以编写包装函数,而我编写的包装函数将具有不同的名称-例如,reverseStringWrapper,而在reverseString中将只有一行-return reverseStringWrapper(str,size( str)-1,“”);
string reverseStringWrapper(string str,ans);
}
string reverseString(string str) {
return reverseStringWrapper(str,size(str) - 1,"");
}
,
最近怎么样?
- 在c中,您可以使用strrev()函数反转字符串(char *)
- 在c ++中,您可以使用std :: reverse()或StringBuilder.reverse()
反转字符串的方法。
。
这样,您可以反转char数组(char *)。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char *str)
{
std::reverse(str,str + strlen(str));
}
// main function
int main()
{
/* using C string */
char s[] = "Hello World";
reverse(s);
cout << "Reverse of the given string is : " << s;
return 0;
}
通过这种方式可以反转字符串。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char* str)
{
std::reverse(str,str + strlen(str));
}
// main function
int main()
{
/* using C string */
// char s[] = "Techie Delight";
string s = "hello world";
int n = s.length();
// declaring character array
char char_array[n + 1];
// copying the contents of the
// string to char array
strcpy(char_array,s.c_str());
reverse(char_array);
s = char_array;
cout << "Reverse of the given string is : " << s;
return 0;
}
希望这可能会有所帮助:)
本文链接:https://www.f2er.com/3029671.html