【问题标题】:Compare two strings in C++在 C++ 中比较两个字符串
【发布时间】:2016-01-04 14:52:10
【问题描述】:

我想将用户输入与存储在字符串数组中的值进行比较。我的数组是

string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};

用户输入分配给

CString selectedColor;

如何比较这些值?

【问题讨论】:

  • 你想知道什么? selectedColor 是否包含在 colours[] 数组中?或者你说的比较是什么意思?
  • 你为什么不坚持一个单一的字符串类?然后,您可以使用关系运算符来做任何您想做的事情。
  • selectedColur 是为用户输入提供的变量名称。我想检查它是否在颜色数组中。
  • string(假设您的意思是std::string)不同,CString 不在 C++ 标准库中。您需要阅读所使用的任何库的文档。很可能会有一些能力从中获得char *const char *。这样的指针可以用来创建std::string,然后你可以使用标准技术进行比较。

标签: c++ arrays if-statement visual-studio-2008


【解决方案1】:

我会做什么:

#include <iostream>

int main(void)
{
    std::string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};
    std::string input;
    std::cin >> input;
    for(const auto& color : colours) //c++11 loop, you can use a regular loop too
    {
        if(input == color)
        {
            std::cout << input << " is a color!" << std::endl;
        }
    }
}

您也可以将CString 转换为std::string 并进行比较,或者反过来将std::string 转换为CString 并进行比较,但这已经被问及回答了:How to convert CString and ::std::string ::std::wstring to each other?

【讨论】:

  • 我正在从组合框(下拉列表)中获取此用户输入。我可以将组合框输入类型从 CString 转换为字符串吗?
  • @AlokaKulathilaka 是的,您可以,只需点击链接或更好地将您的 colours 数组声明为 CString 数组并完全避免转换。免责声明:我对 VC++ 的经验为零(这是我假设您正在使用的)
【解决方案2】:

另一种可能的解决方案,已经完成了所有转换:

std::string colours[] = { "Black", "Blue", "Green", "Orange", "Red", "Yellow" };
CString selectedColor("Blue");

int colours_size = sizeof(colours) / sizeof(colours[0]);
for (int i = 0; i < colours_size; ++i) {
    CString comparedColor(colours[i].c_str());
    if (selectedColor.Compare(comparedColor) == 0) {
        std::cout << "Color found" << std::endl;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多