关于c ++:String解析特定格式

String Parse for a specific format

本问题已经有最佳答案,请猛点这里访问。

string = std::vector(6,0),希望显示为{ 0 0 0 0 0 0 }

我试过这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;


int main()
{
    string str ="std::vector<int>(6,0)" ;

    unsigned found = str.find('(');
    char c = str[found+1];
    int i = c - '0';
    char ch = str[found+3];
    int j = ch - '0';

    str ="{";
    for(int k = 0; k < i ; k++)
    {
        str = str + ch +"" ;
    }

    str = str +" }";

    cout << str << endl;

    return 0;
}

它起作用,但看起来效率不高。有更好的主意吗?


下面是代码的另一个版本,它(希望)更灵活一些。它找到"(sing,then")",用逗号拆分它们,去掉所有空格字符,并将数字转换为整数。然后打印出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <string>
#include <iostream>
using namespace std;

//these three functions are taken from here:
//http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring

#include  
#include <functional>
#include <cctype>
#include <locale>

static inline std::string &ltrim(std::string &s) {
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        return s;
}

// trim from end
static inline std::string &rtrim(std::string &s) {
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
}

// trim from both ends
static inline std::string &trim(std::string &s) {
        return ltrim(rtrim(s));
}

int main()
{
    string s ="std::vector<int>(612,30)";

    int paren_start = s.find("(")+1;

    string numbers = s.substr(paren_start, s.find(")")-paren_start);
    int comma_pos = numbers.find(",");

    string first_num = numbers.substr(0, comma_pos);
    string second_num = numbers.substr(comma_pos+1, numbers.size()-comma_pos);

    int first = atoi(trim(first_num).c_str());
    int second = atoi(trim(second_num).c_str());

    cout <<"{" << endl;
    for(int i=0; i<first; i++)
    {
        cout << second <<"";
    }
    cout <<"}" << endl;

    return 0;
}


当前版本的代码只适用于矢量大小和元素大小的单个数字值。使用std::stringstream获得更好的解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <sstream>

using namespace std;


int main()
{

  string str ="std::vector<int>(6,0)" ;

  unsigned found = str.find('(');
  string arguments = str.substr(found);

  // Replace non-numeric chars with spaces.
  for (unsigned i=0;i<arguments.size(); ++i) {
    if (!isdigit(arguments[i])) {
      arguments[i] = ' ';
    }
  }

  std::istringstream iss(arguments);
  int size;
  // String to avoid having to cast later on
  string value;
  iss >> size >> value;

  string res ="{;

  for (int i = 0; i < size; ++i) {
    res +="
" + value;
  }
  res +="
}";

  cout << res;
  return 0;
}