C语言 小技巧函数方法总结

1.使用^(异或) 不引入第三变量交换两个变量的值。

/* 交换 int a 和 int b 的值*/
#include <stdio.h>

int main(int argc, char *argv[])
{
        int a = 11;
        int b = 22;

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

        printf("a = %d\n",a);
        printf("b = %d\n",b);
        return 0;
}

运行结果
[root@192 clang]# gcc changeVal.c
[root@192 clang]# ./a.out
a = 22
b = 11

 

2.字符串操作

/* 将字符串path = “/root/tmp/as.scv” 截取为 /root/tmp/as后,再拼接添加_static 为 /root/tmp/as_static */
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char *path = "/root/tmp/as.scv"; char *newname = "static"; char last[300] = {0};
strncpy(last,path,(strlen(path)
- strlen(strrchr(path,'.')))); sprintf(last,"%s_%s",last,newname); printf("newname = %s\n",last); return 0; }


运行结果:

[root@192 clang]# gcc stringtes.c
[root@192 clang]# ./a.out
newname = /root/tmp/as_static

 

  

 

 

 

 

posted @ 2019-03-03 18:31  茫茫明明  阅读(338)  评论(0编辑  收藏  举报