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

 

  

 

 

 

 

转载于:https://www.cnblogs.com/mingyue605/p/10466816.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值