-4

编写函数 bitwise_swap 的定义,该函数仅使用按位赋值运算符来交换两个字符串的值。

我尝试遍历每个字符,更改为 int 并使用

a ^= b;
b ^= a;
a ^= b;

一旦我有了 char int 值,但它似乎不起作用。

在此先感谢您的帮助

4

2 回答 2

4

听起来您尝试过这样的事情,应该可以正常工作。

void bitwise_swap(char * restrict lhs, char * restrict rhs, size_t length) {
    size_t i;
    for (i=0; i<length; ++i) {
        lhs[i] ^= rhs[i];
        rhs[i] ^= lhs[i];
        lhs[i] ^= rhs[i];
    }
}
于 2013-06-28T08:58:49.873 回答
1
#include <stdio.h>
#include <string.h>
//#include <stdbool.h>

    int main()
    {  int m,n,t,i;
        char a[]="National University";
        char b[]="India";
        char c[100];
        char d[100];

        m=strlen(a);
        n= strlen(b);


        if(m>n)
        {   t=m;
         //   strcpy(&c,&a);
            for(i=0;i<n;i++)
              d[i]=b[i];
            for(i=0;i<m-n;i++)
                d[n+i]=32;
            for(i=0;i<t;i++)
                   {
                    a[i]=a[i]^d[i];
                    d[i]=d[i]^a[i];
                    a[i]=a[i]^d[i];
                   }

            printf("a= %s \t b=%s" ,a,d);
        }
        else
        {   t=n;
       // strcpy(&d,&b);
           for(i=0;i<m;i++)
               c[i]=a[i];
           for(i=0;i<n-m;i++)
            c[m+i]=32;
           for(i=0;i<t;i++)
                {
                                c[i]=c[i]^b[i];
                                b[i]=b[i]^c[i];
                                c[i]=c[i]^b[i];
                            }

           printf("c= %s \t d=%s" ,c,b);
        }



    return 0;
    }

这样你就可以做到。你只需要一个循环来交换每个字符。编辑:现在它是动态的。您无需手动指定长度,我在较短字符串的末尾附加了 NULL 字符。查看结果:http: //ideone.com/B7lsz4

于 2013-06-28T09:00:37.380 回答