交换两个c字符串

时间:2015-02-15 21:30:38

标签: c++

我试图交换两个cstrings的值,但我一直在犯错误。起初我尝试使用for循环来单独交换每个数组中每个元素的值,但现在我尝试使用strcpy()函数。我不知道自己做错了什么。非常感谢任何帮助!

#include <iostream>
using namespace std;
void exchange(char * &, char * &);
int main()
{
    char * s1 = "Hello";
    char * s2 = "Bye Bye";

    exchange(* & s1, * & s2);

    cout << "s1 = " << s1 << endl; //"Bye Bye" should be displayed
    cout << "s2 = " << s2 << endl; // "Hello" should be displayed
    return 0;
}
void exchange(char * & p1, char * & p2)
{
    int size;
    if (strlen(*& p2) > strlen(*& p1))
    {
        size = strlen(*& p2);
    }
    else
    {
        size = strlen(*& p1);
    }

    char * temp;
    temp = new char[size];

    strcpy(*&temp, *&p1);
    strcpy(*&p1, *&p2);
    strcpy(*&p2, *&temp);
}

2 个答案:

答案 0 :(得分:0)

您需要像std::swap这样的解决方案:

std::swap(s1, s2);

输出将是:

s1 = Bye Bye
s2 = Hello

答案 1 :(得分:-2)

我想通了,我只需要做,而不是功能交换中的所有内容,放:

char * temp;
temp = new char[];

temp = p1;
p1 = p2;
p2 = temp;
相关问题