【问题标题】:C++: Find matching characters in character arrayC++:在字符数组中查找匹配的字符
【发布时间】:2013-07-19 14:05:11
【问题描述】:

如何实现c++脚本从字符数组中搜索一组字符。搜索字符不区分大小写。例如,我键入“aBc”,字符数组有“abcdef”,它是命中并显示找到的。

这是我的脚本,不知道哪里出了问题。

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

int main()
{
  char charArr1[]="abcdefghi";
  char inputArr[20];

  cin>>inputArr;
  charArr1.find("abc");
}

我收到了这个错误。 在'charArr1'中请求成员'find',它是非类类型'char [10]

【问题讨论】:

  • 有什么理由不使用std::string?这会容易得多。

标签: c++ arrays string search


【解决方案1】:
  1. 复制您的输入并将其转换为小写(请参阅How to convert std::string to lower case?
  2. 执行常规搜索 (http://www.cplusplus.com/reference/string/string/find/)

【讨论】:

  • 抱歉垃圾邮件,我是新来的。感谢您的回复!
  • 您发布的链接中的答案不正确,并且会调用未定义的行为(至少在许多平台上)。您不能使用char 调用::tolower
【解决方案2】:

最简单的解决方案是将输入转换为小写,然后 使用std::search

struct ToLower
{
    bool operator()( char ch ) const
    {
        return ::tolower( static_cast<unsigned char>( ch ) );
    }
};

std::string reference( "abcdefghi" );
std::string toSearch;
std::cin >> toSearch;
std::transform( toSearch.begin(), toSearch.end(), toSearch.begin(), ToLower() );
std::string::iterator results
    = std::search( reference.begin(), reference.end(),
                   toSearch.begin(), toSearch.end() );
if ( results != reference.end() ) {
    //  found
} else {
    //  not found
}

ToLower 类应该在您的工具包中;如果你做任何 文本处理,你会用到很多。你会注意到类型 转换;这是必要的,以避免由于未定义的行为 ::tolower 有点特殊的接口。 (根据 您所做的文本处理类型,您可能需要将其更改为 在std::locale 中使用ctype 方面。你也可以避免 有趣的演员,但课程本身将不得不进行一些多余的 bagage 保留指向 facet 的指针,并使其保持活动状态。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多