C++ 将一个字符串的索引与另一个字符串进行比较? [英] C++ comparing the index of a string to another string?
本文介绍了C++ 将一个字符串的索引与另一个字符串进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何比较字符串中的单个字符和另一个字符串(可能大于一个字符,也可能不大于一个字符)
How can I compare a single character from a string, and another string (which may or may not be greater than one character)
这个程序给了我将近 300 行的随机错误.错误也没有引用特定的行号,只是很多关于char*"、"或std::to_string"的内容.
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char* ", "", or "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](这是一个字符)转换为字符串,然后才能将其与另一个字符串进行比较.这是一个简单的方法来做到这一点
You need to convert str[4] (which is a char) to a string before you can compare it to another string. Here's a simple way to do this
if (test == string(1, str[4])) {
这篇关于C++ 将一个字符串的索引与另一个字符串进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文