所以我有一个数组,看起来是这样的:
std::string Operators[4] = {
"+",
"-",
"*",
"/"
};我还有一根绳子,看上去像这样
std::string Equation = "1+1";我试图让代码检查来自数组的加号是否在等式字符串中。这和在字符串中找到子字符串没有什么不同吗?任何帮助都是非常感谢的。
发布于 2022-04-09 02:19:04
通过std::string类的成员函数,特别是,为了您的目的,检查搜索成员函数。
下面是使用find类的std::string成员函数在方程中寻找操作符的一个例子
#include <string>
#include <iostream>
int main()
{
std::string Operators[4] = {
"+",
"-",
"*",
"/"
};
std::string Equation = "1+1";
for (std::size_t i = 0; i < sizeof(Operators)/sizeof(Operators[0]); ++i) {
std::string::size_type n = Equation.find(Operators[i]);
std::cout << Operators[i] << " : ";
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found at position : " << n << '\n';
}
}
return 0;
}输出:
# ./a.out
+ : found at position : 1
- : not found
* : not found
/ : not found注意,在上面的程序中,如果将Operators数组的类型更改为
char Operators[4] = {
'+',
'-',
'*',
'/'
};如果不进行任何其他更改,它将非常好地工作,因为find成员函数有一个过载,它以char作为参数。
发布于 2022-04-09 01:03:58
据我所见,这似乎没有什么不同。也许问题在于评论者所说的,将字符串数组更改为字符数组。无论如何,这段代码适用于您的场景:
int main() {
std::string str = "1+1";
char Operators[4] = {'+','-','*','/'}; // using the commenters suggestion, char array is better
for (int i = 0; i < 4; i++) {
for (int j = 0; j < str.length(); j++) {
if (Operators[i] == str[j])
std::cout << "A '" << Operators[i] << "' is present" << std::endl;
}
}
return 0;
}正如另一位评论者所言,您也可以使用迭代器。
发布于 2022-04-09 01:10:07
使用find_first_of
std::string Equation = "1+1";
std::size_t found = Equation.find_first_of("+-/*");如果找到char,“found”将是偏移量(在本例中为1)。如果未找到,则“found”将等于std::string::npos
看见
要知道找到哪个操作员,请执行
char op = Equation[found];https://stackoverflow.com/questions/71804110
复制相似问题