实现一个函数(判断一个单词是否在一个字符串里面)

本题的核心就是通过双层循环,判断是否字符串中的一部分等于单词;

#include<stdio.h>
#include<Windows.h>
#include<string.h>
bool IswordInString(char* str, char* word) {
    
    
	int lenstr = strlen(str);   //字符串的长度
	int lenword = strlen(word);//单词的长度
	for (int i = 0;i < lenstr;i++) {
    
    
		for (int j = 0;j < lenword;j++) {
    
    
			if (str[i + j] != word[j])
				break;
			if (j == lenword - 1)
				return true;
		}
	}
	return false;
}
int main() {
    
    
	char str[100];
	char word[10];
	printf("请输入字符串:\n");
	gets_s(str);
	printf("请输入单词:\n");
	gets_s(word);

	if (IswordInString(str, word)) {
    
    
		printf("单词在其中\n");
	}
	else {
    
    
		printf("单词不在其中\n");
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_49324123/article/details/111879803