寻找子串(使用strstr)(c语言)

题目描述:

输入两个字符串s1和s2,请在s1中找到s2第一次出现的位置(s2首字符在s1中的下标)。如果不存在则输出”no”。

输入格式:

两个字符串x,y,中间用空格分开。 长度不超过100

输出格式:

输出一个数字或者"no"。

输入样例:

abc a

输出样例:

0

AC代码:

1.头文件

#include <bits/stdc++.h>
using namespace std;
int main(){

 2.定义数据

	char a[10000],b[10000];

3.输入数据

	cin>>a>>b;

 4.过程及输出

	if(strstr(a,b)){
		cout<<(strstr(a,b)-a);
	}else{
		cout<<"no";

 5.结束

	return 0;
}

完整代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	char a[10000],b[10000];
	cin>>a>>b;
	if(strstr(a,b)){
		cout<<(strstr(a,b)-a);
	}else{
		cout<<"no";
	}
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用C语言字符串函数实现字符串的查找和替换。 1. 查找字符串 可以使用strstr函数来查找字符串是否包含指定的子字符串。该函数的原型如下: ```c char* strstr(const char* str1, const char* str2); ``` 其,str1是要查找的字符串,str2是要查找的子字符串。如果str2存在于str1,则返回str2在str1第一次出现的位置的指针;否则返回NULL。 例如,以下代码演示了如何查找字符串是否包含指定的子字符串: ```c #include <stdio.h> #include <string.h> int main() { char str1[] = "Hello, world!"; char str2[] = "world"; char* p = strstr(str1, str2); if (p != NULL) { printf("'%s' is found in '%s' at position %ld.\n", str2, str1, p - str1); } else { printf("'%s' is not found in '%s'.\n", str2, str1); } return 0; } ``` 输出结果为: ``` 'world' is found in 'Hello, world!' at position 7. ``` 2. 替换字符串 可以使用strcpy和strcat函数来实现字符串的替换。具体步骤如下: - 先将原字符串的前缀复制到一个新的字符串; - 然后将要替换的字符串复制到新的字符串; - 最后将原字符串的后缀复制到新的字符串。 例如,以下代码演示了如何将字符串的指定子字符串替换为新的字符串: ```c #include <stdio.h> #include <string.h> int main() { char str1[] = "Hello, world!"; char str2[] = "world"; char str3[] = "everyone"; char* p = strstr(str1, str2); if (p != NULL) { char new_str[100] = {0}; strncpy(new_str, str1, p - str1); strcat(new_str, str3); strcat(new_str, p + strlen(str2)); printf("'%s' is replaced to '%s'.\n", str2, str3); printf("Old string: %s\n", str1); printf("New string: %s\n", new_str); } else { printf("'%s' is not found in '%s'.\n", str2, str1); } return 0; } ``` 输出结果为: ``` 'world' is replaced to 'everyone'. Old string: Hello, world! New string: Hello, everyone! ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值