使用 strcpy 交换字符串

Swap strings using strcpy

我正在尝试仅使用指针表示法(无数组)来交换两个字符串,其中 一个看起来像这样的函数

void str_switch(char *a, char *b)

无论 b 和 a 的大小如何,交换都应该有效,目前尚不清楚。

我的想法是这样的:

void str_switch(char *a, char *b) {
const char *temp = a;
strcpy(b, temp);
}

然而,在这之后,我不确定如何将b复制到a,因为b改变了,我尝试声明其他常量指针,但是一旦我改变了b,我就永远无法获得旧版本。

如果您不想分配额外的存储空间,则需要一次交换一个字符来切换字符串。

如果您可以分配额外的存储空间,strdup a,strcpy b 到 a,strcpy a 的副本到 b,然后 free 副本。

这偏离了您的问题,特别是标题 strcpy 未被使用,请按照您对 Martin James 的评论:

void str_switch(char **a, char **b) {
    char *tmp = *a;
    *a = *b;
    *b = tmp;
}

如果你真的想使用 strcpy,你必须知道 C-strings 的大小。

如果您的字符串使用 malloc() 等函数存储在分配的内存中;因此这段代码非常适合这种情况,特别是因为它 处理具有不同大小和长度的字符串

    #include <stdio.h> // list of libraries that need to be included
    #include <stdlib.h> 
    #include <string.h> 

    void str_switch(char **a, char **b) {
    if (strlen(*a)>strlen(*b)) // check the strings with lowest size to reallocate
    {                          // in order to fit the big one
        char *temp=malloc((strlen(*a)+1)*sizeof(char)); // temp variable to preserve the lowest 
                                                    // the variable with lowest length                           
        strcpy(temp,*a); // store the longest string in its new location
        strcpy(*a,*b);
        free(*b); // free the allocated memory as we no longer need it
        *b=temp; // assign the new address location for the lowest string 
    }
    else if (strlen(*b)>strlen(*a)) // the same as above but invert a to b and b to a
    {
        char *temp=malloc((strlen(*b)+1)*sizeof(char));
        strcpy(temp,*b);
        strcpy(*b,*a);
        free(*a);
        *a=temp;
    }
    else // if the lengths are equal ==> @Morpfh solution
    {
        char *tmp = *a;
        *a = *b;
        *b = tmp;
    }
 }

这是对上述功能的测试(主要代码)

int main(int argc, char *argv[])
{
    char *a=malloc(sizeof(char)*6);
    strcpy(a,"hello");
    char *b=malloc(sizeof(char)*4);
    strcpy(b,"bye");
    printf("a=%s\nb=%s\n",a,b);
    str_switch(&a,&b);
    printf("----------------------\n");
    printf("a=%s\nb=%s\n",a,b);


    return 0;
}

我们得到

a=hello
b=bye
----------------------
a=bye
b=hello