This article collects some practical writing methods, and this blog will continue to be updated and completed
Table of contents
sscanf()——read the data in the string and save it in a certain format
Bit operations - parity judgment
Bit operations - swap two numbers
Bit operations - x to the nth power
C language - implement split() function
C language - determine whether a string is all numbers
sscanf()——read the data in the string and save it in a certain format
// #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() - splicing strings
// #include <stdio.h>
char res[16] = "";
sprintf(res, "%s-%d", "abc", 123);
printf("res = %s\n", res);
Bit operations - parity judgment
int res = 10;
// 10 & 1 --> 0000 1010 & 0000 0001 --> 0000 0000 最终结果为 0 , 即 10 & 1 = 0
if(res & 1)
printf("奇数\n");
else
printf("偶数\n");
Bit operations - swap two numbers
int a = 0, b = 1;
a ^= b;
b ^= a;
a ^= b;
printf("a = %d, b = %d\n", a, b);
Bit operations - x to the nth power
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 language - implement split() function
// #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 language - determine whether a string is all numbers
// #include <string.h>
char str[8] = "1234567";
if(strspn(str, "0123456789") == strlen(str)){
printf("全数字\n");
}else{
printf("非全数字\n");
}