簡體   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