蓝桥杯学习记录-21.3.20
字符串和日期基础3
字符串:是一种常用的数据类型。末尾以\0结束的字符型数组称为字符串,否则只能称为字符型数组,在C中用“%s"输出;在C++中用string类型对字符串进行操作。
字符串复制:char *strcpy(char *destin,char *source)
#include <stdio.h>
#include <string.h>
int main()
{
char name[10];
char *str ="www";
strcpy(name,str);
printf("%s\n",name);
return 0;
}
字符串连接:char*strcat(char *dest,char *source)
#include <string.h>
#include <stdio.h>
int main()
{
char dest[10];
char *str1 ="hello",*str2 =" ",*str3 ="wwww";
strcat(dest,str1);
strcat(dest,str2);
strcat(dest,str3);
printf("%s\n",dest);
return 0;
}
字符串比较strcmp
#include <string.h>
#include <stdio.h>
int main()
{
char *str1 = "cd",*str2="abc";
int res=strcmp(str1,str2);
if(res>0)
{
printf("%s>%s\n",str1,str2);
}
else if(res==0)
{
printf("%s=%s\n",str1,str2);
}
else
{
printf("%s<%s\n",str1,str2);
}
return 0;
}
字符串长度strlen
对称字符串
1、问题描述
问题描述
输入一个正整数N(N<=20)
样例输入
1
样例输出
A
样例输入
2
样例输出
ABA
样例输入
3
样例输出
ABACABA
样例输入
4
样例输出
ABACABADABACABA
2、解题思路
(1)注意res数组定义在main函数外面
3、代码
#include <string.h>
#include <stdio.h>
char res[5000000];
int main()
{
int n;
scanf("%d",&n);
int len=0;
int i;
for(i=1;i<=n;++i)
{
strcat(res+len+1,res);
res[len]='A'+i-1;
len=strlen(res);
}
printf("%s\n",res);
return 0;
}
二、查找字符串
1、题目描述
样例输入
i miss you!
you
样例输出
1
样例输入
ossosso
osso
样例输出
2
2、解析
(1)注意fgets取得字符串后求长度时要减1
3、代码
#include <cstring>
#include <cstdio>
char s1[1005],s2[1005];
int main()
{
fgets(s1,1004,stdin);
fgets(s2,1004,stdin);
int len1=strlen(s1)-1,len2=strlen(s2)-1;
int ans=0;
for(int i=0;i<len1-len2+1;++i)
{
bool matched=true;
for(int j=0;j<len2;j++)
{
if(s1[i+j]!=s2[j])
{
matched=false;
break;
}
}
if(matched)
{
ans++;
}
}
printf("%d\n",ans);
return 0;
}