1

需要帮忙

这是我的代码

void swapstringfun()
{
   int i=0,j=0;
   char *str=(char *)malloc(sizeof(char)*15);
   char *mystr=(char *)malloc(sizeof(char)*15);
   system("cls");
   printf("Please enter first string :\t");
   scanf("%s",str);
   printf("Please enter second string :\t");
   scanf("%s",mystr);
   while(*(str+i)!='\0' && *(mystr+i)!='\0')
   {
     *(str+i) ^=*(mystr+i);
     *(mystr+i) ^=*(str+i);
     *(str+i) ^=*(mystr+i);
     i++;
   }
   printf("%s swapped to %s",str,mystr);
   getch();
   main();
}

我编写了上面的代码来使用 XOR 运算符交换字符串。这段代码的问题是。当我的输入是让我们说.. RAJESHASHISH。然后,它显示输出ASHISHRAJESH。而且,这是意料之中的。

但是,当输入说.. ABHISHEKCODER时,输出是CODERHEKABHIS。但是,预期的输出是CODERABHISHEK。任何人都可以帮我解决这个问题。我会感激的。

4

3 回答 3

2

You iterate and swap until you reach the end of the shorter string

while(*(str+i)!='\0' && *(mystr+i)!='\0')

(or both, if the lengths are equal). To iterate until you reach the end of the longer string, you need an || instead of the && and be sure that 1. both pointers point to large enough memory blocks, and 2. the shorter string ends with enough 0 bytes. So you should calloc the memory, not malloc.

However, you should swap the pointers, really,

char *tmp = str;
str = mystr;
mystr = tmp;
于 2012-11-04T16:31:39.463 回答
1

You also need to swap the terminating 0, as its part of what is called a string in C.

The 0 is the stopper element in the character array, describing the string.

于 2012-11-04T16:32:00.070 回答
0

You need to XOR the entire length of both strings. Since in your second example, the strings are different lengths, your algorithm won't work.

This is the statement you'll have to reconsider:

while(*(str+i)!='\0' && *(mystr+i)!='\0')
于 2012-11-04T16:33:11.217 回答