字符串相关函数的使用
1.字符串连接字符
strcat(s1,s2);两个字符串连接操作//猫猫连接字符串
2.字符串求长度字符
strlen(s1);可以直接求长度
3.在s1中找s2存在的位置 若存在返回出现的第一个位置 否则返回-1;
strstr(s1,s2);
4将s2复制到s1中去
strcpy(s1,s2)
char ch1[]="abcde";//C字符串
char ch2[10];//数组
strcpy(ch2,ch1);//编译是通过的,不过ch2会从数组变成字符串.因为strcpy会在数组最后加'\0'标记
如果你所说的字符串是string也就是c++字符串,你可以先使用string的c_str()函数将string换为c形字符串再复制。
对于strcpy函数 若strcpy(s,&a[100])其中a[100]是字符串 因为该函数会自动给数组加‘0凑 从100开始到最后
题目描述
你需要开发一款文字处理软件。最开始时输入一个字符串(不超过 100 个字符)作为初始文档。可以认为文档开头是第 0 个字符。需要支持以下操作:
-
1 str
:后接插入,在文档后面插入字符串 str,并输出文档的字符串。 -
2 a b
:截取文档部分,只保留文档中从第 a 个字符起 b 个字符,并输出文档的字符串。 -
3 a str
:插入片段,在文档中第 a 个字符前面插入字符串 str,并输出文档的字符串。 -
4 str
:查找子串,查找字符串 str 在文档中最先的位置并输出;如果找不到输出 -1。
为了简化问题,规定初始的文档和每次操作中的 str 都不含有空格或换行。最多会有 q(q\le100)q(q≤100) 次操作。
输入格式
无
输出格式
无
输入输出样例
输入 #1复制
4 ILove 1 Luogu 2 5 5 3 3 guGugu 4 gu
输出 #1复制
ILoveLuogu Luogu LuoguGugugu 3
答案
#include<cstdio> #include<cstring> #define MAXN 101 char s[MAXN],in[MAXN]; int main() { int n; scanf("%d\n%s",&n,s); for(int i=1;i<=n;i++){ int opt; scanf("%d",&opt); if(opt==1){ scanf("%s",in); strcat(s,in); printf("%s\n",s); }else if(opt==2){ int a,b; scanf("%d %d",&a,&b); s[a+b]='\0'; strcpy(in,&s[a]); strcpy(s,in); printf("%s\n",s); }else if(opt==3){ int a; scanf("%d %s",&a,in); strcat(in,&s[a]); s[a]='\0'; strcat(s,in); printf("%s\n",s); }else{ scanf("%s",in); char*ans=strstr(s,in); if(ans!=NULL){ printf("%d\n",int(ans-s)); }else{ printf("%d\n",-1); } } } return 0;
’