2015-10-02 90 views
-4

我怎么能检查下面的文本块的每行字3正如在一起,然后保存该行有它检查一次出现在字符串中相同字符的

12345ArAcAd21 
32A293AaAbAc3 
AaAcAd8922113 
Aa34442108131 

我提取各行成字符串数组,每行的大小是13,有4行。在上面的文本块中,我们可以看到第1,2,3行有3Ax,其中x是一个随机字符。 所以我想获得数字1,2,3。

我该怎么做?

现在在这里我取得了

bool occur = true; 
      for (size_t i = line.find("A"); i != string::npos; i = line.find("A", i + 2)) { 
       if (line[i + 2] == 'A') { 
        for (int x = 0; x < 3; x++) { 
         if (line[i + x + 2] != 'A') { 
          occur = false; 
          break; 
         } 
        } 
       } else { 
        // skips it 
        continue; 
       } 
      } 
+1

绝对没有在溶液中做出的努力。这是非常基本的C++。 – CoffeeandCode

+0

把字符串放在一个向量中,并遍历向量并使用['find'](http://en.cppreference.com/w/cpp/string/basic_string/find)来查找子字符串? –

+0

@CoffeeandCode对不起,我已更新我的问题。 – Ravensmith450

回答

1

在代码中,你已宣布出现为bool,然后你再宣布它作为一个int。可能这就是它不工作的原因。

您可以使用正则表达式很容易地解决这个问题。 Google“C++正则表达式”获取更多细节。你也可以问我是否有任何困惑。我给根据您在下面输入一个代码示例:

#include <iostream> 
#include <regex> 
#include <string> 
using namespace std; 

int main() 
{ 
    string str[4]; 
    str[0] = "12345A5AcAd21"; 
    str[1] = "32A293AaAbAc3"; 
    str[2] = "AaAcAd8922113"; 
    str[3] = "Aa34442108131"; 

    for(int i=0; i<4; i++) { //for each string 
     string line = str[i]; 

     regex e1(".*A.A.A.*"); //pattern = AxAxAx in any part of the string 
     bool match = regex_match(line, e1); 
     if(match) { 
      cout << i << ": " << line << endl; 
      //enter your code here 
     } 
    } 

    return 0; 
} 

输出:

0: 12345ArAcAd21 
1: 32A293AaAbAc3 
2: AaAcAd8922113 
+0

谢谢,如果AbAdAc呢? Ax,其中x是随机字母表。 – Ravensmith450

+0

在AbAdAc中,3A不在一起。所以情况不会是真的。但我认为你只想要3A在一起。 :-o –

+0

是的,如果它是这样的,我是否需要找到A的每个出现,并检查下一个3 A(索引+ 2)是否现在有2个字符。例如AbAdAc,A是索引0,+ 2索引3其仍然是A,依此类推。我的逻辑正确吗? – Ravensmith450

相关问题