C++将一个字符串的索引与另一个字符串进行比较
C++ comparing the index of a string to another string?
如何比较字符串中的单个字符和另一个字符串(可能大于也可能不大于一个字符)
这个程序给了我近 300 行随机错误。 这些错误也没有引用特定的行号,只是很多关于"char*"、""或"std::to_string"的东西。
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
>str[4]
是一种char
类型,无法与string
进行比较。
比较苹果和苹果。
用
test[0] == str[4]
相反。
您需要将 str[4](这是一个字符)转换为字符串,然后才能将其与另一个字符串进行比较。这是一个简单的方法来做到这一点
if (test == string(1, str[4])) {
您正在将字符与 std::string 进行比较,这不是有效的比较。您正在寻找 std::string::find,如下所示:
if( test.find( str[4] ) != std::string::npos ) cout << test << "n";
请注意,如果测试包含 str[4]
,这将返回 true。
您正在混合类型。它不知道如何将字符串(test
)与字符(str[4]
)进行比较。
如果将测试更改为正常工作的char
。或者引用要比较的测试中的特定字符,例如它应该编译和运行if (test[0] == str[4])
。
但是,由于这只是一个示例,而不是真正的问题,因此您要做的是查看std::string
类提供的功能。
如果你像这样比较它,你还需要"D"
是一个字符值而不是一个字符串值。
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
您必须将其转换为字符数组才能访问它。除非你这样做。
str.at(i);
你也可以写成
str[i]
<——你做了什么。
从本质上讲,这一切都归结为测试需要像char test = 'D';
一样初始化
最终输出..
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
char test = 'D';
if (test == str[4]) { // This line causes NO problems
cout << test << endl;
}
return 0;
}
我认为你可能将python与c ++混合在一起。在 c++ 中,'g'
是指单个字符g
而不是长度为 1 的字符串。"g"是指长度为 1 个字符且看起来像 ['g'] 的数组(字符串)。如您所见,如果将单个字符与字符数组进行比较,无论数组长度是否为单个字符,则不会定义此操作。
如果通过构建一个能够将一个字符长度的字符串与单个字符进行比较的类来自己定义它,这将起作用。或者只是重载==
运算符来做到这一点
例:
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
bool operator == ( const string &lh, const char &rh) {
if (lh.length() == 1) return lh[0] == rh;
return 0;
}
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) {
cout << test << endl;
}
else cout << "Not a matchn";
return 0;
}
- 按字母顺序对C++问题中的子字符串索引进行分区
- C++ 中字符串向量的索引
- C++ - 成功打印超出范围的字符串索引
- 对于循环增量器不能用作字符串向量的索引
- 如何检索由带通配符的字符串索引的对象
- 访问包含P的有效索引时返回空格的C++字符串
- 在我的 for 循环中,如何将索引更改为字符串?
- 有效地从文本文件中读取带有字符串索引的大型二维数组(矩阵)
- 如何使用调整后的字符串索引第二次通过循环运行字符串
- C++中的字符串索引问题
- Qt5.5 Q奇数结果的字符串索引
- 是否有理由使用字符串 => 索引到向量的映射,而不是字符串 => 对象?
- 在数组 C++ 中搜索字符串索引
- C++:字符串索引和保留标点符号时出现问题
- C++中类似python的字符串索引
- 如何在c++中高效地实现PHP字符串索引数组
- 如果访问了错误的字符串索引,c++不会抛出错误
- C++中的 Unicode 字符串索引
- 如何按索引为 c++ 字符串索引赋值
- 在 C++ 中使用字符串索引的整数