如何查找子字符串或字符串文字

时间:2017-09-07 15:49:28

标签: c++ string

我正在尝试编写一个代码,用于搜索userInput中的单词" darn"如果找到了,打印出来"截尾"。如果找不到,它只会打印出userInput。它在某些情况下有效,但在其他情况下无效。如果userInput是"那就是猫!",它将打印出来"截尾"。但是,如果userInput是" Dang,这是可怕的!",它还打印出"截尾"。我正在尝试使用find()来搜索字符串文字" darn" (这个空间是因为它应该能够确定单词" darn"和类似" darning"之类的单词。我并不担心标题符号" darn") 。然而,似乎find()没有做我想做的事情。有没有其他方法可以搜索字符串文字?我尝试使用substr(),但我无法弄清楚索引和len应该是什么。

fooList.Where(s => s.columnOne == "someString");

2 个答案:

答案 0 :(得分:5)

这里的问题是你的病情。 std::string::find返回std::string::size_type的对象,该对象是无符号整数类型。这意味着它永远不会小于0,这意味着

if (userInput.find("darn ") > 0)

始终为true,除非userInput"darn "开头。因此,如果find找不到任何内容,则会返回std::string::npos。您需要做的是与

进行比较
if (userInput.find("darn ") != std::string::npos)

请注意userInput.find("darn ")在所有情况下都不起作用。如果userInput只是"darn""Darn",那么它就不会匹配。空间需要作为单独的元素处理。例如:

std::string::size_type position = userInput.find("darn");
if (position != std::string::npos) {
    // now you can check which character is at userInput[position + 4]
}

答案 1 :(得分:0)

std::searchstd::string::replace是为此而做的:

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

using namespace std;

int main() {
    string userInput;

    userInput = "That darn cat is a varmint.";

    static const string bad_words [] = {
            "darn",
            "varmint"
    };

    for(auto&& bad : bad_words)
    {
        const auto size = distance(bad.begin(), bad.end());
        auto i = userInput.begin();
        while ((i = std::search(i, userInput.end(), bad.begin(), bad.end())) != userInput.end())
        {
            // modify this part to allow more or fewer leading letters from the offending words
            constexpr std::size_t leading_letters = 1;

            // never allow the whole word to appear - hide at least the last letter
            auto leading = std::min(leading_letters, std::size_t(size - 1));

            auto replacement = std::string(i, i + leading) + std::string(size - leading, '*');
            userInput.replace(i, i + size, replacement.begin(), replacement.end());
            i += size;
        }
    }

    cout << userInput << endl;

    return 0;
}

预期产出:

That d*** cat is a v******.