本文章收藏一些实用的写法,本博客会继续更新补全
目录
sscanf()——读取字符串中的数据,并以一定的格式保存下来
C语言——判断字符串是否为全数字
sscanf()——读取字符串中的数据,并以一定的格式保存下来
// #include <stdio.h>
int res = 0;
char src[10] = "1234";
// 实现 atoi() 的功能
// atoi() 和 itoa() 定义在 strlib.h 中,但是 itoa() 函数无法在 linux 中使用
sscanf(src, "%d", &res);
printf("res = %d\n", res);
sprintf()——拼接字符串
// #include <stdio.h>
char res[16] = "";
sprintf(res, "%s-%d", "abc", 123);
printf("res = %s\n", res);
位运算——奇偶性判断
int res = 10;
// 10 & 1 --> 0000 1010 & 0000 0001 --> 0000 0000 最终结果为 0 , 即 10 & 1 = 0
if(res & 1)
printf("奇数\n");
else
printf("偶数\n");
位运算——两数交换
int a = 0, b = 1;
a ^= b;
b ^= a;
a ^= b;
printf("a = %d, b = %d\n", a, b);
位运算——x的n次方
int x = 10, n = 3, res = 1;
while (n) {
if (n & 1 != 0)
res *= x;
x *= x;
n = n >> 1;
}
printf("res = %d\n", res);
C语言——实现 split() 功能
// #include <string.h>
char src[20] = "123.456.789", *res = NULL;
// strtok() 拥有记忆功能,之后传入 NULL ,则会继续使用之前裁剪的数据
res = strtok(src, ".");
printf("res = %s\n", res);
while (res)
{
res = strtok(NULL, ".");
printf("res = %s\n", res);
}
// 输出为 123 456 789 null
C语言——判断字符串是否为全数字
// #include <string.h>
char str[8] = "1234567";
if(strspn(str, "0123456789") == strlen(str)){
printf("全数字\n");
}else{
printf("非全数字\n");
}