东华大学 2022 oj c++ 无超纲写法 求字符串的起始位置

 //两种写法,一种用了系统内置的find函数,非常简便

//还有一种是我最开始写的,只有一组测试数据的一个过不了,后来改过了,是没问题的,详细解释在代码段里

find函数写法:

#include<iostream>
#include<string>
#include<bits/stdc++.h>
using namespace std;
//find函数的话前面的remove 和exist都不需要的
void remove(char a[], int n)//a为给定数组,n为初始有效元素个数
{
	for (int i = 0; i < n - 1; i++)
	{
		a[i] = a[i + 1];
	}
}//做一个删除字符串首项的函数
int exist(char a[], char b[], int n)//a为长数组,b为短数组,n为b的长度
{
	int len = strlen(a);
	int m = len;
	int cnt = 1;
	while (strncmp(a, b, n) != 0)
	{
		remove(a, len);
		len--;
		cnt++;
		if (len == 0)
		{
			return (0);
		}
		if (strlen(a) < strlen(b))
		{
			return 0;
		}
	}
	
	return (cnt); 
}
int main()
{//ceshi
	/*char a[10];
	cin.getline(a, 10);
	remove(a, 5);
	for (int i = 0; i < 4; i++)
	{
		cout << a[i];
	}*/

	string s1, s2;
	while (cin>>s1)
	{
		cin>>s2;
		/*int k = strlen(s2);
		int p = strlen(s1);*/
		if (s1.find(s2) != string::npos)
		{
			cout << s1.find(s2) + 1 << endl;
		}
		else { cout<<0<< endl; }
		/*if (exist(s1, s2, k) == 1)
		{
			cout << 0 << endl;
		}
		else
		{
			cout << exist(s1, s2, k) << endl;
		}*/
	}
	//system("pause");
	return 0;
}

大致思路:

//这个方法的大致思路我个人认为就是find函数的char版,对于给定的a b两数组
//a是长的,b是短的,我们利用strcmp函数,比较a与b的前n项(n就是b的长度)
//如果不相等,就删除a的首项,直到找到了为止(利用cnt计数)
//开始有一组测试数据是“abckk" "kkk",按理说是没有的,但是我却输出了4
//最后发现remove函数写的不彻底,应该把最后一项改为'\0',不然的话,a数组
//的长度是没有变化的,“abckk”会变为“kkkkk”
//改过之后是AC的,供大家参考

#include<iostream>
#include<string>
#include<bits/stdc++.h>
using namespace std;
void remove(char a[], int n)//a为给定数组,n为初始有效元素个数
{
	for (int i = 0; i < n - 1; i++)
	{
		a[i] = a[i + 1];
	}
	a[n - 1] = '\0';//最初我没有写这一行,发生了错误
}//做一个删除字符串首项的函数
int exist(char a[], char b[], int n)//主要的函数
{
	int len = strlen(a);
	int m = len;
	int cnt = 1;
	while (strncmp(a, b, n) != 0)
	{
		remove(a, len);
		len--;
		cnt++;
		if (len == 0)
		{
			return (0);
		}
	}

	return (cnt);
}
int main()
{//ceshi
 /*char a[10];
 cin.getline(a, 10);
 remove(a, 5);
 for (int i = 0; i < 4; i++)
 {
 cout << a[i];
 }*/

	char s1[120] = { '\0' }, s2[120];
	while (cin.getline(s1, 120))
	{
		cin.getline(s2, 120);
		int k = strlen(s2);
		int p = strlen(s1);

		cout << exist(s1, s2, k) << endl;
		/*if (exist(s1, s2, k) == 1)
		{
		cout << 0 << endl;
		}
		else
		{
		cout << exist(s1, s2, k) << endl;
		}*/
	}
	//system("pause");
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值