首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在数组中找到字符串中的对象?

如何在数组中找到字符串中的对象?
EN

Stack Overflow用户
提问于 2022-04-08 23:39:01
回答 3查看 90关注 0票数 1

所以我有一个数组,看起来是这样的:

代码语言:javascript
复制
std::string Operators[4] = {
  "+",
  "-",
  "*",
  "/"
};

我还有一根绳子,看上去像这样

代码语言:javascript
复制
std::string Equation = "1+1";

我试图让代码检查来自数组的加号是否在等式字符串中。这和在字符串中找到子字符串没有什么不同吗?任何帮助都是非常感谢的。

EN

回答 3

Stack Overflow用户

发布于 2022-04-09 02:19:04

通过std::string类的成员函数,特别是,为了您的目的,检查搜索成员函数。

下面是使用find类的std::string成员函数在方程中寻找操作符的一个例子

代码语言:javascript
复制
#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; 
}

输出:

代码语言:javascript
复制
# ./a.out
+ : found at position : 1
- : not found
* : not found
/ : not found

注意,在上面的程序中,如果将Operators数组的类型更改为

代码语言:javascript
复制
char Operators[4] = {
  '+',
  '-',
  '*',
  '/'
};

如果不进行任何其他更改,它将非常好地工作,因为find成员函数有一个过载,它以char作为参数。

票数 1
EN

Stack Overflow用户

发布于 2022-04-09 01:03:58

据我所见,这似乎没有什么不同。也许问题在于评论者所说的,将字符串数组更改为字符数组。无论如何,这段代码适用于您的场景:

代码语言:javascript
复制
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;

}

正如另一位评论者所言,您也可以使用迭代器。

票数 0
EN

Stack Overflow用户

发布于 2022-04-09 01:10:07

使用find_first_of

代码语言:javascript
复制
 std::string Equation = "1+1";

 std::size_t found = Equation.find_first_of("+-/*");

如果找到char,“found”将是偏移量(在本例中为1)。如果未找到,则“found”将等于std::string::npos

看见

of/ of/

要知道找到哪个操作员,请执行

代码语言:javascript
复制
   char op = Equation[found];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71804110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档