strstr:
先看看定义:char *strstr(const char *haystack, const char *needle)
-->haystack -- 要被检索的 C 字符串。
-->needle -- 在 haystack 字符串内要搜索的小字符串。
如果看不懂,那接下来实操来了解他吧~
#include<stdio.h>
#include<string.h>//strstr函数的头文件
int main()
{
char s[100] = "wyf is cute";
char* p = strstr(s, "is");
printf("%s", p);
return 0;
}
代码运行结果:
如果输入%s就会输出所查找字符串后面所有直至“\0”的字符串
那么,换成%d呢?
没错,就是字符串所在的位置!
话不多说,直接上例题,练练记忆会深刻呐(光说不练假把式)
聪明的你一定看出来是把you换成we了吧
解题思路:
要解决的问题:找到目标字符并替换成新字符,替换后整体长度会发生变化,我们可以 用一个新的数组来取得我们需要的,丢弃我们不要的
#include<stdio.h>
#include<string.h>
char s[100];
char str[200];//放外边不仅可以自动初始化,
//还可以减少main函数里栈空间的使用
int main()
{
char t;
while (gets(s) != NULL)
{
char a[10] = "you";
char b[10] = "we";
int i = 0, j = 0, t;
while (i < strlen(s))
{
if (strstr(&s[i], a) == &s[i])//查找是否存在目标子串
{
for (t = 0; t < strlen(b); t++)
str[j++] = b[t];//存储要替换字符串
i += strlen(a);//找到字符串后,在从该字符串后检索
}
else
str[j++] = s[i++];
}
s[j] = '\0';
puts(str);//此输出函数输出自动换行
}
return 0;
}
字符串的插入:
如果不清楚sprintf函数,可以看看下面哟~
有了sprintf函数一切就简单了
#include<stdio.h>
#include<string.h>
char t[100];
char s[100];
char str[100];
int main()
{
int i;
gets(t);
gets(s);//被插入函数
int pos;
scanf("%d", &pos);
sprintf(str, "%*s%s", pos, s, t);
for ( i = 0; i < strlen(str); i++)
{
printf("%c", str[i]);
}
puts(s + pos);
return 0;
}
对于字符串的插入还有一种思路,提供代码仅供参考,如果有更好的,我们评论区一起讨论啊^^
#include<stdio.h> char s[100];//被插入函数 char t[100]; int main() { scanf("%s%*c",s);//数组可以不用取地址, //数组本身就是地址; //(%*c)可以读取结尾多余的换行符) scanf("%s",t); int n; scanf("%d",&n); int i,j; for( i=0;i<strlen(s);i++) { if(i+1==n) { for( j=0;j<strlen(t);j++) { printf("%c",t[j]); } } printf("%c",s[i]); } return 0; }
运行结果:
下期见~