首页 > 解决方案 > 字符串不落在另一个字符串中间的逻辑

问题描述

当我希望我的字符串不落在另一个字符串的中间时,我需要帮助找出逻辑或代码。例如,我给定的单词是“生日!” 另一个要查找的字符串是“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;
}

标签: c++

解决方案


这是一个超级简单的程序供您查看。

对于这个问题,你所要做的就是使用 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,您使用 == 表示未找到的内容,使用 != 表示已找到的内容。


推荐阅读