如何交换在函数中作为指针传递的 2 个字符串

How to swap 2 strings passed as pointers in a function?

本文关键字:指针 字符串 何交换 交换 函数      更新时间:2023-10-16

我必须将作为指针传递给函数的 2 个字符字符串交换:布尔swap_strings(字符* 字符串 1、字符* 字符串 2)如果两个字符串的长度不同,则返回 false,否则如果交换有效,则返回 true;

我怎样才能意识到这一点?为什么这是不正确的:

#include <iostream>
using namespace std;

bool swap_strings(char * string1, char * string2) { 
    char * s;
    char * s2;
    char * tmp = nullptr;
        for (s = string1; *s != ''; ++s);
        for (s2 = string2; *s2 != ''; ++s2);
        if ((s - s2)  != 0) {
            return false;
        }
        else {      
            tmp = *&string1;
            string1 = *&string2;
            string2 = *&tmp;
            cout << tmp << string1 << string2<< endl;
        }
        return true;
    }

int main()
{
    bool da = false;
    char s1[] = "hallo1";
    char s2[] = "ababab";
    da = swap_strings(s1, s2); 
    cout << da << s1 << s2 <<endl;
}   

除非你想复制已经编写的代码,否则你需要使用 strlen 来获取字符串的长度:

unsigned int s1len = strlen(string1);
unsigned int s2len = strlen(string2);
if (s1len != s2len)
    return false;

如果您无法使用标准库函数(愚蠢的要求):

unsigned int s1len = 0;
for (char* s = string1; *s != ''; s++, s1len++);

将做同样的事情(你必须对两个字符串都这样做)。

之后,交换很简单:

for (unsigned int i = 0; i < s1len; ++i)
{
    std::swap(string1[i], string2[i]);
}

for (unsigned int i = 0; i < s1len; ++i)
{
    // these 3 lines are identical to what is done in std::swap
    char t = string1[i];
    string1[i] = string2[i];
    string2[i] = t;
}

您也可以(毫无疑问,破坏分配的目的),只需更改指针值:

bool swap_strings(char*& string1, char*& string2)
{
    char* t = string1;
    string1 = string2; // string1 will now point to string2
    string2 = t; // string2 will now point to what use to be string1
    return true;
}

我说它违背了作业的目的,因为你没有做任何复制,当你这样做时,长度要求是无关紧要的。 当您传入数组时(例如,如果您将输入声明为 char a[] = "abcd"; - 您在main中已经这样做),它也不会工作(例如不会编译)。

您可以简单地循环遍历传递的字符串,然后进行逐个字符交换。

例如

#include <assert.h>
#include <iostream>
bool swap_strings(char * const s1, char * const s2) {
    assert(s1 != nullptr);
    assert(s2 != nullptr);
    if (strlen(s1) != strlen(s2))
        return false;
    char * pch1 = s1;
    char * pch2 = s2;
    char temp;
    while (*pch1 != '') {
        temp = *pch1;
        *pch1 = *pch2;
        *pch2 = temp;
        ++pch1;
        ++pch2;
    }
    return true;
}
int main() {
    using namespace std;
    char s1[] = "hallo1";
    char s2[] = "world2";
    if (swap_strings(s1, s2)) {
        cout << s1 << endl;
        cout << s2 << endl;
    }
}