c++ - 如何在 C++ 中的字符串数组中查找单词位置?

标签 c++ arrays location

对于我正在编写的程序,我需要在字符串数组中找到特定单词的位置,但我不知道如何做。这是我编写的代码,但它不起作用:

 int location;
 string input;

 cout << "Type your name" << endl;
 cin >> input;

  for (int i = 0; i <= count; i++) 
    {
        call_DB[i].name;

    if (call_DB[i].name == input)
        {
            location = i;
        }
    }

该代码有什么问题,我该如何解决?谢谢。

最佳答案

试试 std::find_if,它在数组中搜索满足提供的预测函数的项目。

auto iter = std::find_if(call_DB, call_DB + count, [&input](const YOUR_CALL_DB_TYPE& item ){ return item.name == input; });

if(iter == call_DB + count) 
     printf("Not found\n");
else
     printf("Found: %s\n", iter->name.c_str());

如果找到这样的项目,索引是到数组基址的距离,size_t index = iter - call_DB;

关于c++ - 如何在 C++ 中的字符串数组中查找单词位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42942100/

相关文章:

java - 使用随机整数创建多维数组

Java - 3D 数组修剪方法起作用

python - 使用空格分隔符连接多个 numpy 字符串数组

Android:基于位置的应用程序

android - IllegalArgumentException : provider doesn't exisit: null on Maps V1

c++ - 为什么这两个代码片段会给出不同的结果

c++ - 为什么静态 main() 类型的程序显示错误?

c++ - 在 C/C++ 中打印所有 ASCII 值

java - isProviderEnabled() 永远不会被调用 android

iphone:我应该学什么?