如何在包含 10 个元素的字符串数组中查找字符串

How to find a string in a string array of 10 elements

我正在尝试创建一个函数,要求用户提供他们正在寻找的 DVD 标题,该标题位于以下格式的文本文件中:

标题:类型:价格

文本文件中有 10 行都遵循该格式。 我首先将每一行放入一个包含 10 个元素的数组中。

我有一张 DVD class,它具有我正在尝试创建的函数 getTitle():

void DVD::getTitle(){
    cout << "Type the title of the dvd you're looking for." << endl;
    cin >> title;

    for(int i = 0; i < 10; i++){ //Loop through the dvd array object.

        if(dvd[i].find(title)){ //Test if the title entered is in any of the array elements
            cout << "We have " << title << " in stock." << endl;
        }
    }
    cout << "Sorry we don't have that title." << endl;
}

此函数在 main 中调用 DVD class object。我知道查找函数 returns 是一个迭代器 元素一旦找到,但我无法弄清楚如何在找到元素后打印出该元素。 我的输出只是将标题的第一个单词(Free Willy 中的"Free")写了 9 次,而不是仅在 它在数组元素之一中找到 Free Willy。 我也尝试使用

for(int i = 0; i < 10; i++){ //Loop through the dvd array object.

    //Attempt to search each array element up to the colon, and place the 
    //strings before the colon in dvdTest.
    getline(dvd[i], dvdTest, ':');

    //Test if the string elements before the colon are the same as the title entered.
    if(dvdTest == title){
        cout << "We have " << title << " in stock." << endl;
    }
}
cout << "Sorry we don't have that title." << endl;

为了尝试将直到冒号的所有当前数组元素放入 dvdTest 变量中,然后我测试了 if(dvdTest == title),然后打印出标题是否有货。 我得到一个错误,说没有匹配函数来调用 getline,所以我认为 getline 不适用于数组。 然后我尝试了

for(int i = 0; i < file.eof(); i++){ //Loop through the lines in the file.

    //Get strings from the current line up to the colon, place into dvdTest.
    getline(file, dvdTest, ':');

    if(dvdTest == title){ //Test if dvdTest and the title entered are the same.
        cout << "We have " << title << " in stock." << endl;
    }
}
cout << "Sorry we don't have that title." << endl;

我尝试输入 Avatar(文本文件中的第 5 个标题),它只是输出 "Sorry we don't have that title.",所以它要么没有找到 Avatar,要么每次通过时都在检查文件的第一行for循环? 是否有可能以类似的方式完成我正在尝试做的事情,或者这是完全错误的方法,我应该以不同的方式来完成吗?

我已经连续 3 天每天花几个小时检查整个 cplusplus 的文件使用情况、getline、find,但我什么都想不通。

将字符串放入 vector and utilize the std::find 函数中:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main(){
    std::vector<std::string> v{ "Movie 1", "Movie 2", "Movie 3" };
    std::cout << "Enter the movie title to find: ";
    std::string whattofind;
    std::getline(std::cin, whattofind);
    auto found = std::find(v.begin(), v.end(), "Movie 2");
    if (found != std::end(v)) {
        std::cout << "v contains: " << whattofind << '\n';
    }
    else {
        std::cout << "v does not contain: " << whattofind << '\n';
    }
}

如果你想使用数组然后使用 std::beginstd::end 函数,然后是 std::find:

std::string movies[] = { "Movie 1", "Movie 2", "Movie 3" };
std::string whattofind = "Movie 2";
auto found = std::find(std::begin(movies), std::end(movies), "Movie 2");
if (found != std::end(movies)) // ... same as above

您不能单独使用 std::cin 从标准输入中接受字符串。您需要改用 std::getline 函数:

std::string tempstr;
std::getline(std::cin, tempstr);

如果您使用的是 C 字符串,const char*,您必须 使用 strcmp(str1, str2):

#include <string>
...
bool found = false;

//Loop through the dvd array object
for(int i = 0; !found && i < 10; i++){ 
    //Is the title entered in any of the array elements?  
    found = (strcmp(dvd[i].title, title) == 0;
}

if (found)
    cout << "We have " << title << " in stock." << endl;
else
    cout << "Sorry we don't have that title." << endl;

否则,只需比较 std::strings 使用 ==:

//Loop through the dvd array  object.
for(int i = 0; !found && i < 10; i++){ 
    //Is the title entered in any of the array elements?  
    found = (dvd[i].title == title);
}

if (found)
    cout << "We have " << title << " in stock." << endl;
else
    cout << "Sorry we don't have that title." << endl;

问题是 cin >> title 没有读整行。 它只读取字符,直到到达空格。

要读入整行输入,您必须使用:

std::string line;
while ( std::getline(cin, line) ) 
{
    // .... do something with line
}

如何使用 line 做某事? (代码中的超链接)

1) 您可以使用line.find(':') to find the semi colon positions and then use line.substr(pos_from, char_count)提取子字符串。

2) 可以使用正则表达式std::regex("([^:]*):([^:]*):([^:]*)") to split this string up. And then use regex_match 提取特定片段。

3) Other options ...


编辑: 解释正则表达式(tutorial)

  1. 第一个括号 - 匹配不是冒号的所有内容,这是匹配组 1
  2. 匹配冒号
  3. 第二个括号 - 匹配不是冒号的所有内容,这是匹配组 2
  4. 匹配冒号
  5. 第三个括号 - 匹配不是冒号的所有内容,这是匹配组 3

代码:

// Extraction of a sub-match (matching group) 
const std::regex match_regex("([^:]*):([^:]*):([^:]*)");
std::smatch matched_strings;

if (std::regex_match(line, matched_strings, match_regex)) {
     std::string first_match = matched_strings[1].str();
     std::string second_match = matched_strings[2].str();
     std::string third_match = matched_strings[3].str();
}