比较字符和常量字符串

Compare char and const string

本文关键字:字符串 常量 字符 比较      更新时间:2023-10-16

在创建3D引擎的一部分时,我陷入了一个基本的C++问题。

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

问题在第 20 行:test.cpp:20:19:错误:与"运算符=="不匹配(操作数类型为"char"和"const string {aka const std::__cxx11:::basic_string}"(

当我用像"X"这样的文字字符替换 foo 时,它有效。然而,这不是动态的。我试图搜索解决方案并尝试了 .c_str(( 之类的东西,但没有成功。

编辑:foo的类型不能更改,并且必须是std::string const&因为我使用学校的图书馆,其中使用该类型读取配置文件。

您可以明确表示只关心第一个字符。

if (c == foo[0]) 

或者将字符转换为字符串(效率较低(。

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

如果您使用非 ASCII 字符串(unicode 或其他一些多字节表示形式(,这两种方法都会失败。

一些可以处理空字符串的解决方案,但不涉及新std::string的动态分配(尽管智能实现确实避免了小字符串优化的动态分配(:

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

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

如果您不介意依赖小字符串优化,那么这可能更简单:

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