【问题标题】:how to find keyword in string in c++c++中如何在字符串中查找关键字
【发布时间】:2020-04-11 01:09:27
【问题描述】:

当您使用特定关键字时,只需打印出包含该关键字的所有单词。你不应该使用数组来解决问题。

我使用find()函数获取从关键字的起始索引处打印直到出现','的代码,但是出现了错误。

代码如下:

#include <iostream>
#include <string>
#include <limits.h>
using namespace std;

int main() {
    string data = "사랑,프로그래머,의자,사랑의바보,영통역,천년의사랑,냉장고,객체지향";
    string keyword;
    cout << "키워드 : ";
    cin >> keyword;
    int i = 0;
    while (1) {
        i = data.find(keyword, i);
        if (i == INT_MAX) return 0;
        while (data[i] != ',') {
            cout << data[i] << " ";
            i++;
        }
    }
}

即使编译成功,如果关键字在单词后面,也无法打印。

总之,我的问题是:

  1. 上面代码有问题,假设关键字在单词前面。

  2. 即使关键字在后面也能打印单词的想法。

【问题讨论】:

  • std::string::find 如果没有找到任何东西,则返回std::string::npos。不知道是不是和INT_MAX一样。结果是std::size_t 类型而不是int:std::size_t i = 0;
  • 内部while 循环在最后一个单词之后越界:while (i &lt; data.length() &amp;&amp; data[i] != ',')
  • @ThomasSablik INT_MAX (2147483647) 和 std::string::npos ((size_t)-1) 不是同一个值

标签: c++ string keyword


【解决方案1】:

std::string::find 如果没有找到任何东西,则返回std::string::npos。

结果是std::size_t 类型而不是int:std::size_t i = 0;

内部while 循环在最后一个单词之后超出范围:while (i &lt; data.length() &amp;&amp; data[i] != ',')

#include <iostream>
#include <string>
using namespace std;

int main() {
    string data = "사랑,프로그래머,의자,사랑의바보,영통역,천년의사랑,냉장고,객체지향";
    string keyword;
    cout << "키워드 : ";
    cin >> keyword;
    std::size_t i = 0;
    while (1) {
        i = data.find(keyword, i);
        if (i == std::string::npos) return 0;
        while (i < data.length() && data[i] != ',') {
            cout << data[i] << " ";
            i++;
        }
    }
}

【讨论】:

  • 非常感谢您的详细解答。但是,在上传时编辑和编译时,如果我输入关键字,??????是输出。问题是什么?如果一个关键字包含在一个单词的末尾,你应该使用什么想法来打印这个单词?
  • 使用substr 方法将每个单词存储在自己的string 中。例如,不要先在循环中找到keyword,而是先找到分隔符(在您的情况下为","),然后您可以在该单词上使用keyword 执行另一个find。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 2012-11-10
相关资源
最近更新 更多