繁体   English   中英

比较C ++中的两个字符串

[英]Compare two strings in C++

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

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

用户输入分配给

CString selectedColor;

如何比较这些值?

我会怎么做:

#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并进行比较,但这已被问到并回答: 如何转换CString和:: std :: string :: std :: wstring互相吗?

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

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM