比较字符和常量字符串
Compare char and const string
在创建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)
相关文章:
- 将错误作为从字符串常量到"char*"的已弃用转换 [-Wwrite-strings]
- 3 与错误最接近的总和:字符串常量之前的预期非限定 id
- 为什么字符串(常量字符* s,size_t pos,size_t len = npos)有效?
- 指向字符串常量的指针
- 警告:ISO C++禁止将字符串常量转换为'char*' [-Wwrite-strings]
- 为什么在波纹管程序中发生了从字符串常量到'char*'的警告已弃用的转换
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- 如何从字符串常量创建字符数组
- 将字符串常量转换为char
- C++ 字符串常量和静态初始化顺序惨败
- 使用 std::string 返回开关大小写块中的字符串常量
- 消除从字符串常量到'char*'的已弃用转换的最佳方法"
- 警告:ISO C++禁止将静态“constexpr char*”数据成员的字符串常量转换为“char*”
- 字符常量或字符串常量
- Swig:如何类型映射c ++字符串常量和python字符串?
- 字符串常量之前的预期构造函数、析构函数或类型转换
- 为什么从字符串常量到"char*"的转换在 C 中有效,但在C++中无效
- 警告:已弃用从字符串常量到 'char* 的转换
- 无法获得通过C++警告:(和崩溃后)已弃用从字符串常量到"char*"的转换 [-Wwrite-strings]
- 错误:字符串常量 extern "a" { 之前应为非限定 ID