Laity199 2021-06-17 09:02 采纳率: 80%
浏览 20
已采纳

C++用字符数组做题

输入两个字符串s1和s2,在s1中查找s2对应的字符串是否存在,若存在则输出它的第一次出现的位置;若不存在,则输出“没有找到该字符串”。

  • 写回答

1条回答 默认 最新

  • qfl_sdu 2021-06-17 10:05
    关注

    C++代码如下:如有帮助,请采纳一下,谢谢。

    #include <iostream>
    #include <string>
    using namespace std;
    
    //查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
    void findstr(const char*big ,const char* smal,int pos[],int *nmb)
    {
    	int i,j,lenb,lens;
    	lenb = strlen(big);
    	lens = strlen(smal);
    	*nmb = 0;
    	if(lens > lenb)
    		return;
    
    	i = 0;
    	while(i < lenb-lens+1)
    	{
    		for (j = 0; j < lens;j++)
    		{
    			if(tolower(big[i+j]) != tolower(smal[j]))
    				break;
    		}
    		if (j == lens) //说明找到
    		{
    			pos[*nmb] = i;
    			(*nmb)++;
    			i += lens;
    		}else
    			i++;
    	}
    }
    int main()
    {
    	string s1 = "";
    	string s2 = "";
    	int pos[10];
    	int nmb = 0;
    	cout << "请输入两个字符串" << endl;
    	cin >> s1;
    	cin >> s2;
    	findstr(s1.c_str(),s2.c_str(),pos,&nmb);
    
    	if (nmb <= 0)
    	{
    		cout << "没有找到该字符串" << endl;
    	}else
    		cout << "第一个位置:" << pos[0];
    
    	return 0;
    }

    C代码如下

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    
    //查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
    void findstr(char big[] ,char smal[],int pos[],int *nmb)
    {
    	int i,j,lenb,lens;
    	lenb = strlen(big);
    	lens = strlen(smal);
    	*nmb = 0;
    	if(lens > lenb)
    		return;
    
    	i = 0;
    	while(i < lenb-lens+1)
    	{
    		for (j = 0; j < lens;j++)
    		{
    			if(tolower(big[i+j]) != tolower(smal[j]))
    				break;
    		}
    		if (j == lens) //说明找到
    		{
    			pos[*nmb] = i;
    			(*nmb)++;
    			i += lens;
    		}else
    			i++;
    	}
    }
    int main()
    {
    	char s1[100] ={0};
    	char s2[100] = {0};
    	int pos[10];
    	int nmb = 0;
    	printf("请输入两个字符串\n");
    	gets(s1);
    	gets(s2);
    	findstr(s1,s2,pos,&nmb);
    
    	if (nmb <= 0)
    	{
    		printf("没有找到该字符串\n");
    	}else
    		printf("第一个位置:%d\n",pos[0]); 
    
    	return 0;
    }

     

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写