#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void test01(){
char buf[1024];
memset(buf, 0, 1024);
sprintf(buf,"今天是%d年%月%d日\n",2019,10,21);
printf("%s", buf);
//字符串拼接
memset(buf, 0, 1024);
char str1[] = "hello";
char str2[] = "world";
int len = sprintf(buf,"%s%s",str1,str2);
printf("buf:%s len:%d\n",buf,len);
//数字转字符串
memset(buf,0,1024);
int num = 100;
sprintf(buf,"%d",num);
printf("buf:%s\n",buf);
//设置宽度 右对齐
memset(buf,0,1024);
sprintf(buf,"%8d",num);
printf("buf:%s\n",buf);
//设置宽度 左对齐
memset(buf, 0, 1024);
sprintf(buf, "%-8d", num);
printf("buf:%sa\n", buf);
//转成8进制字符串
memset(buf,0,1024);
sprintf(buf,"0%o",num);
printf("buf:%s\n",buf);
}
int main(){
test01();
return 0;
}
sscanfは
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//1.%*s或%*d 跳过数据
void test01(){
char *str = "12345abcde";
char buf[1024] = {0};
sscanf(str,"%*d%s",buf); //abcde
printf("%s\n",buf);
}
void test02(){
char *str = "abcde123456";
char buf[1024] = {0};
//sscanf(str,"%*s%s",buf);
sscanf(str,"%*[a-z]%s",buf);//123456
printf("%s\n",buf);
}
//2.%[width]s 读取指定宽度的数据
void test03(){
char *str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str,"%6s",buf);//12345a
printf("%s\n",buf);
}
//3.%[a-z] 匹配a到z中任意字符(尽可能多的匹配)
void test04(){
char *str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str,"%*d%[a-z]",buf);//abcde
printf("%s\n",buf);
}
//4.%[aBc] 匹配a,B,c中一员,贪婪性
void test05(){
char *str = "aacde12345";
char buf[1024] = { 0 };
sscanf(str,"%[aBc]",buf);//aac,匹配过程中只要失败停止匹配
printf("%s\n",buf);
}
//5.%[^a] 匹配非a的任意字符,贪婪性
void test06(){
char *str = "abcde12345";
char buf[1024] = { 0 };
sscanf(str,"%[^c]",buf); //ab 匹配过程一失败就停止匹配
printf("%s\n",buf);
}
//6. %[^a-z] 表示读取除了a-z以外的所有字符
void test07(){
char *str = "abcde12345";
char buf[1024] = { 0 };
sscanf(str,"%[^0-9]",buf);//abcde
printf("%s\n",buf);
}
//7.案例
void test08(){
char *ip = "127.0.0.1";
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
sscanf(ip,"%d.%d.%d.%d",&num1,&num2,&num3,&num4);
printf("%d\n", num1);
printf("%d\n", num2);
printf("%d\n", num3);
printf("%d\n", num4);
}
void test09(){
char *str = "abced#zhangtao@12345";
char buf[1024] = { 0 };
sscanf(str,"%*[^#]#%[^@]",buf);//zhangtao
printf("%s\n",buf);
}
void test10(){
//已给定字符串为: [email protected],
//请编码实现helloworld输出和com.cn
char *str = "[email protected]";
char buf1[1024] = { 0 };
char buf2[1024] = { 0 };
sscanf(str,"%[a-z]%*[@]%s",buf1,buf2);
printf("%s\n",buf1);
printf("%s\n",buf2);
}
int main(){
test10();
return 0;
}