1.printf和sprintf
printf:输出到屏幕上
sprintf:输出到字符串中
#define _CRT_SECURE_NO_WARNINGS //关闭安全检查
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main1()
{
//char str[100] = "for /l %i in (1,1,5) do calc";
//char *p = "for /l %i in (1,1,5) do calc";
//str[0] = ' ';// str是数组,存储的是字符串每一个字符
//*p = ' ';//error,p是一个指针,存储字符串的地址
char str[100] = { 0 };
//printf("for /l %%i in (1,1,%d) do %s",5,"calc");//printf中%需%%表示,类似的有 \\->\, \"->"
int num;
char op[30] = { 0 };
scanf("%d%s", &num, op);
sprintf(str, "for /l %%i in (1,1,%d) do %s", num, op);
system(str);
system("pause");
}
void main2()
{
char str1[100] = "note";
char str2[100] = "pad";
//system(str1 + str2);
char str3[100] = { 0 };
sprintf(str3, "%s%s", str1, str2);//字符串相加
system(str3);
}
void main3()
{
char str[100] = "notepad8888";
char newstr[100] = "";
sprintf(newstr, "%-10.7s", str);//10宽度,+宽度范围内右边对齐,-左边对齐,.7从左往右挖去7个字符
printf("[%s]", newstr);
system(newstr);
system("pause");
}
2.sscanf:更改字符串的特定内容
void main4()
{
char str[100] = "我有1000元";
int num;
sscanf(str, "我有%d元", &num);
printf("%d", num);
system("pause");
}
3.求字符串的长度
int mystrlen(char* str)
{
int i = 0;
for (char*p = str; *p != '\0'; p++)
{
i++;
}
return i;//实现字符串统计
}
int mystrlenA(char* str)
{
char *p = str;
int i = 0;
AAA: if (*p!='\0')
{
i++;
p++;
goto AAA;
}
return i;
}
int mystrlenB(char *str)
{
if (*str=='\0')
{
return 0;
}
else
{
return 1 + mystrlenB(++str);
}
}
void main123()
{
char str[100] = "china is good";
printf("%d", sizeof(str));//求数组缓冲区长度
printf("\n%d", mystrlen(str));//从开头第一个字符到\0字符
printf("\n%d", mystrlenA(str));//从开头第一个字符到\0字符
printf("\n%d", mystrlenB(str));//从开头第一个字符到\0字符
getchar();
}