0

如何在 C++ 中读取这些行,而不使用正则表达式:

name(numeric_value_or_some_string[, numeric_value_or_some_string]) [name(numeric_value_or_some_string[, numeric_value_or_some_string])]

例如:

 VM(4, 2) VR(7) VP(8, 3) I(VIN)

我很想知道如何轻松检查字符串是否为有效形式。

4

1 回答 1

2

这只是简单的字符串解析,没有魔法:

#include <iostream>
#include <string>
#include <vector>

int main(int argc, char** argv){
  std::string str = "VM(4, 2) VR(7) VP(8, 3) I(VIN)";
  std::string name;
  size_t pos = 0;
  while(pos < str.size()){
    if(str.at(pos) == '('){
      ++pos;
      std::vector<std::string> values;
      std::string currentValue;
      while(pos < str.size()){
        if(str.at(pos) == ')'){
          if(!currentValue.empty()){
            values.push_back(currentValue);
            currentValue.clear();
          }
          break;
        }else if(str.at(pos) == ','){
          if(!currentValue.empty()){
            values.push_back(currentValue);
            currentValue.clear();
          }
        }else if(str.at(pos) == ' '){
          /* intentionally left blank */
          /* ignore whitespaces */
        }else{
          currentValue.push_back(str.at(pos));
        }
        pos++;
      }
      std::cout << "-----------" << std::endl;
      std::cout << "Name: " << name << std::endl;
      for(size_t i=0; i<values.size(); i++){
        std::cout << "Value "<< i <<": " << values.at(i) << std::endl;
      }
      std::cout << "-----------" << std::endl;
      name.clear();
    }else if(str.at(pos) == ' '){
          /* intentionally left blank */
          /* ignore whitespaces */
    }else{
      name.push_back(str.at(pos));
    }
    ++pos;
  }
  return 0;
}

样品的输出:

-----------
Name: VM
Value 0: 4
Value 1: 2
-----------
-----------
Name: VR
Value 0: 7
-----------
-----------
Name: VP
Value 0: 8
Value 1: 3
-----------
-----------
Name: I
Value 0: VIN
-----------
于 2013-11-07T08:58:14.780 回答