【问题标题】:how to include two index value test condition in a for loop?如何在 for 循环中包含两个索引值测试条件?
【发布时间】:2019-03-31 14:27:48
【问题描述】:

如何在for循环中包含两个索引值测试条件?

我希望为数组语法解析一个字符串(分别找到'['和']'的位置)

string arrangements="a[1]";

所以我试图在一个 for 循环中进行时间复杂度的目的。 我试过了

for(int i=0; i<arrangements.size();i++){

if(arranements[i]=='['){
        cout<<"square opening is at : "<<i<<endl;

  while(arrangements[i]==']' ){

  cout<<"square closing is at : "<<i<<endl;
           i++;
        }
}
}

我什至尝试过

for(int i=0; i<arrangements.size();i++){


  while(arrangements[i]==']' && arrangements[i]=='['){

  cout<<"square closing is at : "<<i<<endl;
           i++;
        }
}
}

对不起,我没有与任何人联系,所以谢谢你帮助好人。

【问题讨论】:

  • while(arrangements[i]==']'){ => while(arrangements[i]!=']'){
  • 我建议研究如何编写一个适当的递归体面解析器如何为您要解析的任何内容编写 BNF 语法,然后使用诸如 bison 之类的东西来生成语法分析器。或者,在琐碎的情况下,使用正则表达式。
  • @JesperJuhl 谢谢你的这些关键字,我现在可以去具体点了..

标签: c++ for-loop while-loop


【解决方案1】:

你可以使用find:

for (int i = 0 ; i != arrangements.size(); ++i) {
    if (arranements[i] == '[') {
        std::cout << "square opening is at : " << i << std::endl;
        auto e = arrangements.find(']', i + 1);
        if (e != std::string::npos) {
            std::cout << "square closing is at : " << e << std::endl;
     }
}

【讨论】:

  • 先生,我可以用一些简单的我是初学者,我不想使用 lib 函数,
  • 这是std::string的方法,你已经使用了类。如果不想用,建议重新实现一下。
【解决方案2】:

您可以使用if...else ifswitch

if...else if的情况:

const int size = arrangements.size();
for(int i = 0; i < size; ++i)
{
  const char a = arrangements[i];
  if(a == '[')
    cout << "square opening is at : " << i << endl;
  else if(a == ']')
    cout << "square closing is at : " << i << endl;
}

【讨论】:

  • 谢谢,如果条件再次开始循环,则不会下一步。出于复杂性目的,我们可以在找到“[”之后再去那里吗?
  • @bikashamit,你是什么意思?
  • 我们能不能做一些事情,比如搜索下一个 ']' 会在我们找到 '[' 后追踪索引,我怀疑如果条件重新开始,我可能会错我是初学者。
  • 循环不会因为另一个 if 重新开始。这取决于i,它仅在每一步后递增
猜你喜欢
  • 2011-12-07
  • 1970-01-01
  • 2020-04-29
  • 2017-02-16
  • 2022-09-29
  • 2017-10-22
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多