洛谷P1308 字符串实例

首先介绍一下strstr函数,它是<string.h>中的库函数

定义:strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL

再介绍一下<cctype>头文件

本次解题需要使用的库函数有isupper()函数,它是判断一个字符是否是大写字母的系统函数;tolower是将一个大写字母转换为小写字母。该头文件中还包含众多函数。如下

 

isalnum 检查字符是否为字母数字
isalpha 检查字符是否为字母
isblank (c++ 11) 检查字符是否为空格空白
iscntrl 检查字符是否为控制字符
isdigit 检查字符是否为十进制数
isgraph 检查字符是否有图形输出
islower 检查字符是否为小写字母
isprint 检查字符是否能输出
ispunct 检查字符是否为标点
isspace 检查字符是否为区域空白
isupper 检查字符是否为大写字母
isxdigit 检查字符是否为十六进制的数
字符转换函数:
用来在两个在大小写字母之间转换
tolower 将大写字母转换为小写字母
toupper 将小写字母转换为大写字母

整体代码

#include <cstring>
#include <cctype>
#include <cstdio>
//将一个字符串中的大写字母转换为小写字母
void strlower(char *a)
{

	for(int i=0;a[i];i++)
	{
		if(isupper(a[i])) a[i]=tolower(a[i]);
	}

}

int main()
{
	char word[10];
	char article[1000000];
 	char *q,*p;
 	
 	int ans=0;
 	int position=-1;

 

	gets(word);
	gets(article);

	int len=strlen(word);
//全部转换为小写
	strlower(word);
	strlower(article);

	p=article;

for(;q=strstr(p,word);){
	if(q!=NULL &&  (q==article||*(q-1)==' ')  &&  (*(q+len)=='\0'||*(q+len)==' ')){
		//首先q值不能为空;除了q指针的位置可以在开头以外,要保证q指针的前一位要为空格;最后要保证q+len为空格或者为'\0'。
		ans++;
		if(position==-1){
			position=q-article; //两个指针相减为整形数据
		}
    }
  		p=q+len;//更新p指针的位置,在p指针后再次检索有没有单词word;
}

if(position!=-1)printf("%d %d\n",ans,position);

else printf("%d\n",position);

return 0;

}

  

posted @ 2020-09-17 17:33  守恒丶  阅读(238)  评论(0)    收藏  举报