C++将一个字符串的索引与另一个字符串进行比较

C++ comparing the index of a string to another string?

本文关键字:字符串 索引 另一个 比较 C++ 一个      更新时间:2023-10-16

如何比较字符串中的单个字符和另一个字符串(可能大于也可能不大于一个字符)

这个程序给了我近 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;
}