转换为 C 风格的字符串

Converting to C style String

我正在尝试创建一个函数,它接受一个字符串,将其反转,这一切都在 main 中完成。这是我到目前为止所拥有的。

#include <cstring>
#include <iostream>
#include <string>


std::string str = "zombie";


void Reverse( std::string a)
{

    char* a1 = a.c_str;
    char* a2;

    for (int i = (strlen(a1) -1); a1[i]!=0; i--)
    {
        a2 += a1[i];
    }

    str = a2;
}

int main()
{
    Reverse(str);

    std::cout << str << std::endl;
}

但是我一直收到这个错误。我不能在这个问题上使用指针。有什么建议吗?

编辑:我在将插入的参数 a 转换为 C 风格的字符串时遇到了特别的问题。

编辑 2:所以我开始稍微清理一下,据我所知,即使进行适当的更改,我的代码也根本无法实现我的目标。这会不会走上更好的轨道?我计划在将字符串传递给函数之前将其转换为 C 风格。

void Reverse(const char* s)
{
    int x = strlen(s);
    std::string str = "";

    for (int c = x; c > 0; c--)
    {
        str += s[c];
    }

}

该功能完全无效。

例如参数应该声明为std::string &.

当函数依赖于全局变量时,这是个坏主意。

在此声明中

char* a1 = a.c_str;

同时出现两个错误。首先必须有 a.c_str() 而不是 a.c_str。而成员函数c_strreturns一个常量指针

这个指针

char* a2;

具有不确定的值。

既然你到现在为止对如何用 C++ 编写该函数一无所知,那么我将只展示其实现的几种变体。

最简单的如下

#include <iostream>
#include <string>

std::string & Reverse( std::string &s )
{
    s.assign(s.rbegin(), s.rend());

    return s;
}


int main()
{
    std::string s = "zombie";

    std::cout << s << std::endl;
    std::cout << Reverse(s) << std::endl;

    return 0;
}

该函数使用 class std::string.

的反向迭代器

另一种方法是使用在 header <algorithm>

中声明的标准算法 std::reverse
#include <iostream>
#include <string>
#include <algorithm>

std::string & Reverse(std::string &s)
{
    std::reverse(s.begin(), s.end());

    return s;
}

int main()
{
    std::string s = "zombie";

    std::cout << s << std::endl;
    std::cout << Reverse(s) << std::endl;

    return 0;
}

如果您想使用循环自己编写函数,那么它的实现可能类似于

#include <iostream>
#include <string>


std::string & Reverse(std::string &s)
{
    for (std::string::size_type i = 0, n = s.size(); i < n / 2; i++)
    {
        //std::swap(s[i], s[n - i - 1]);
        char c = s[i];
        s[i] = s[n - i - 1];
        s[n - i - 1] = c;
    }

    return s;
}

int main()
{
    std::string s = "zombie";

    std::cout << s << std::endl;
    std::cout << Reverse(s) << std::endl;

    return 0;
}

在所有三种情况下,程序输出都如下所示

zombie
eibmoz

您也可以尝试使用迭代器(双向或随机)代替索引自己编写函数。