2013-05-01 92 views
-1

所有:C++字符串解析

我在字符串解析一個問題:

現在,如果我有這樣一個字符串「+ 12 + 400-500 + 2:+ 13-50-510 + 20-66 + 20:「

我該如何計算每個分段的總和(:可以考慮爲一個分段的末端)。現在,我可以找出只有通過使用循環和檢查+/-號,但我不認爲這是很好的一個通用的方法來解決這樣的問題:(

For example, the first segment, +12+400-500+2 = -86, and the second segment is 
+13-50-510+20-66+20 = -573 

1) The number of operand is varied(but they are always integer) 
2) The number of segment is varied 
3) I need do it in C++ or C. 

我真的不認爲這是一個非常簡單的問題大多數新手,而且我會要求這不是功課。:)

最好,

+0

的http://計算器。 com/questions/236129/splitting-a-string-in-c – 2013-05-01 22:01:15

+0

這是功課嗎? – Sven 2013-05-01 22:01:39

+0

不,當然不是。 :) – Kuan 2013-05-01 22:03:19

回答

3

由於串中的冒號結束,它很容易使用findsubstr以分離出由':'分隔的字符串的部分,像這樣:

string all("+12+400-500+2:+13-50-510+20-66+20:"); 
int pos = 0; 
for (;;) { 
    int next = all.find(':', pos); 
    if (next == string::npos) break; 
    string expr(all.substr(pos, (next-pos)+1)); 
    cout << expr << endl; 
    pos = next+1; 
} 

此拆分原始字符串分成部分

+12+400-500+2: 

+13-50-510+20-66+20: 

由於istream。就拿領先加以及前導負,可以解析出使用>>運營商的數字:

istringstream iss(expr); 
while (iss) { 
    int n; 
    iss >> n; 
    cout << n << endl; 
} 

有了這兩個部分在手,你可以很容易達到了個體數,併產生預期的輸出。這是一個quick demo

+0

謝謝,dasblinkenlight !,我會試試這個。 – Kuan 2013-05-02 13:54:43

+0

這真是太神奇了,我是C++的新手,你能告訴我如何以及在哪裏可以找到這種特殊用法?或者你能給我一些關於「C++祕密」的鏈接嗎? – Kuan 2013-05-02 14:05:46

+0

@Kuan C++絕對沒有任何祕密,它只是需要一段時間才能「獲得」它。你可以在線找到關於各種C++類的信息。例如,'std :: string'在[here](http://www.cplusplus.com/reference/string/string/)中有描述; 'std :: istringstream'是[here](http://www.cplusplus。COM /參考/ sstream/istringstream /)。 – dasblinkenlight 2013-05-02 14:12:10

1

你需要單獨的操作數和運算。爲此,您可以使用兩種隊列數據類型,一種用於操作數,另一種用於運算符

+0

有什麼細節嗎? – Kuan 2013-05-01 22:07:02

0

:分開,然後按+,然後按-。翻譯成int,你就在那裏。

0

你的表達式語言似乎定期:你可以使用正則表達式庫 - 像boost::regex - 要匹配的數字,符號和直接組段,像

((([+-])([0-9]+))+)(:((([+-])([0-9]))+))+