文章目录
字符串处理函数
string.h 文件中的函数
字符串复制 strcpy strncpy
// str1 的空间要足够大,能容纳str2
strcpy(str1,str2);
puts(str1);
// 复制前 n 个字节,要自己补’\0’
strncpy(str1,“123456789”, 2);
puts(str1);
字符串比较 strcmp strncmp
// 比较str1 和 str2,函数返回值
// 1、str1 > str2 : 返回值 > 0
// 2、str1 == str2 : 返回值 = 0
// 3、str1 < str2 : 返回值 < 0
if (strcmp(str1, str2) == 0)
{
printf (“相等\n”);
}
printf ("------------------------\n");
// 比较前 n 个字节是否相等
if (strncmp(str1, str2, 4) == 0)
{
printf (“相等\n”);
}
字符串粘贴 strcat strcat
// 字符串2粘贴到字符串1的后面
// 注意:字符串1必须要足够大,否则会导致数组越界
strcat(str1, str2);
puts(str1);
// 将字符串2的前 n个字节 粘贴到字符串1的后面
strncat(str1, “12345678”, 2);
puts(str1);
字符串转整型 atoi
char str[] = “123a”;
int a = atoi(str);
printf (“a = %d\n”, a);
格式化字符串 sscanf sprintf
char str[100] = {0};
sprintf(str, “a = %d, b = %d”, a, b);
puts(str);
char str[] = “a = 10 b = 20”;
sscanf(str, “a = %d b = %d”, &a, &b);
练习:
1、将ip转整数输出
// 将ip转换成整数
// ip ===> int
unsigned int func1(char *ps)
{
unsigned int n1;
unsigned int n2;
unsigned int n3;
unsigned int n4;
sscanf (ps, "%u.%u.%u.%u", &n1, &n2, &n3, &n4);
printf ("%u.%u.%u.%u\n", n1, n2, n3, n4);
//unsigned int num = n1*256*256*256 + n2*256*256 + n3*256 + n4;
unsigned int num = (n1<<24) + (n2<<16) + (n3<<8) + n4;
return num;
}
2、将整数转ip输出
> // 将整数转换成字符串
// ip ===> int
void func2(int num, char *ps)
{
unsigned int n1 = (num>>24) & 0xFF;;
unsigned int n2 = (num>>16) & 0xFF;;
unsigned int n3 = (num>>8) & 0xFF;
unsigned int n4 = num & 0xFF;
sprintf(ps, "%d.%d.%d.%d", n1, n2, n3, n4);
}