我试图用指针符号(没有数组)交换两个字符串
像这样的函数
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,我就永远无法得到旧版本。
最佳答案
如果字符串使用类似于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