c++ - 字符串不落在另一个字符串中间的逻辑
问题描述
当我希望我的字符串不落在另一个字符串的中间时,我需要帮助找出逻辑或代码。例如,我给定的单词是“生日!” 另一个要查找的字符串是“Happy Birthday Scott”。它将返回一个错误值,因为它缺少一个感叹号。这是我工作过的代码
int Words::matchWords(const char* string, const char* sentence, int wordNum){
int wordCount = words(sentence); // the words function counts the number of words in the sentence
int strLength = strlen(str);
int sentLength = strlen(sentence);
int i = 0;
char strTemp[100];
char sentenceTemp[100];
strcpy(strTemp, str);
strcpy(sentenceTemp, sentence);
if (wordNum > wordCount) {
return false;
}
char* temp;
for (i = 0; i < strLength; i++) {
strTemp[i] = tolower(str[i]);
}
for (i = 0; i < sentLength; i++) {
sentenceTemp[i] = tolower(str[i]);
}
temp = strstr(sentenceTemp, strTemp);
if (temp != NULL) {
return true;
if (strTemp[i] != sentenceTemp[i]) {
return false;
}
else
return true;
}
else
return false;
}
解决方案
这是一个超级简单的程序供您查看。
对于这个问题,你所要做的就是使用 std::string 创建你的字符串,使用 find() 确定它们是否在大字符串中,最后使用 string::npos 检查是否找到它。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string bday = "Birthday!";
string str1 = "Happy Birthday Scott";
int found1 = str1.find(bday);
string str2 = "Scott, Happy Birthday!";
int found2 = str2.find(bday);
if (found1 == string::npos) //if Birthday! is NOT found!
{
cout << "str1: " << "FALSE!" << endl;
}
if (found2 != string::npos) //if Birthday! IS found!
{
cout << "str2: " << "TRUE!" << endl;
}
}
请注意,对于 string::npos,您使用 == 表示未找到的内容,使用 != 表示已找到的内容。
推荐阅读
- shell - 捕获“bmaptool”的进度百分比
- mysql - 从 mysql 表中查找唯一联系人
- python - 为什么 python 用这个语句返回 false?
- c++ - 如何在 Rcpp 中乘以 S4 对象?缺少运算符定义
- typescript - 首先声明键 ("key1" | "key2"),然后强制另一个对象类型必须具有这些键
- scala - Scala:模式匹配案例类的圈复杂度太高
- javascript - 如何使用 passport-google-oauth20 获取用户电子邮件
- javascript - (REACT) 优化 API 调用链导致组件不渲染
- javascript - Jquery Datatable 分页按钮样式修复
- aws-amplify - AWS Amplify 创建多个具有重复信息的 DynamoDB 表?