字符串简单应用

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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值