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

Compare two strings in C++

本文关键字:两个 字符串 c++ 比较      更新时间:2023-10-16

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

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