简体   繁体   中英

Compare char and const string

In the context of creating a part of an 3D-engine I'm stuck in a basic C++ problem.

#include <iostream>

//Ignore this function
std::string get_replacement(char c) {return "TEEEEEEEST";}

int main() {
    //Declaring some variables
    std::string const& foo = "X";
    std::string str = "FFFFGGGGXFFWEFWXFFFF";
    const int N = 4;    //Amount of iterations
    //These values and types can't be changed
    //----------------------------------------


    //String before changement
    std::cout << "Before: " << str << std::endl;

    for (int i = 0; i < N; i++) {
        for (char c : str) {
            if (c == foo) {     //How to do this????
                str += get_replacement(c);
            } else str += c;
        }   
    }   

    std::cout << "After: " << str << std::endl;

}

The problem is on line 20: test.cpp:20:19: error: no match for 'operator==' (operand types are 'char' and 'const string {aka const std::__cxx11::basic_string}')

It works when I replace foo with a literal character like 'X'. However that is not dynamic. I tried to search a solution and tried stuff like .c_str() but without success.

Edit: The type of foo can't be changed AND MUST BE std::string const& because I use a library of school where a configuration file is read with that type.

You can make it explicit that you only care about the first character.

if (c == foo[0]) 

Or convert the character to a string (this is less efficient).

if (std::string(1, c) == foo)

Both methods fail miserably if you work with non-ascii strings (unicode or some other multi byte representation).

A few solutions that can deal with empty strings, but also doesn't involve dynamic allocation of a new std::string (although, smart implementations do avoid dynamic allocation with small string optimization anyway):

if(foo().size() == 1
&& c == foo.front())

Or

char str[] = {c, '\0'};
if (str == foo)

If you don't mind relying on small string optimization, then this is perhaps simpler:

if (std::string{c} == foo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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