如何使用STL算法計算從指定位置開始的段落中的字數?使用STL的字數
Q
使用STL的字數
0
A
回答
2
#include <algorithm>
#include <cctype>
#include <functional>
#include <string>
inline unsigned CountWords(const std::string& s)
{
std::string x = s;
std::replace_if(x.begin(), x.end(), std::ptr_fun <int, int> (std::isspace), ' ');
x.erase(0, x.find_first_not_of(" "));
if (x.empty()) return 0;
return std::count(x.begin(), std::unique(x.begin(), x.end()), ' ') + !std::isspace( *s.regin());
}
+0
對於那些需要解釋這個優秀答案的人來說,以下可能會有所幫助。 std :: replace_if用空格替換所有的空白字符。擦除調用會從字符串的開頭剝離所有空白字符。對std :: unique的調用返回一個新的字符串,其中刪除所有連續的重複空格。對std :: count的調用返回由std :: unique返回的字符串中的空格數量和單詞數量。最後根據原始字符串是否在空格中開始,將0或1添加到結果計數中。 – 2015-06-28 05:35:21
0
int count_words(const char *input_buf) {
stringstream ss;
ss << input_buf;
string word;
int words = 0;
while(ss >> word) words++;
return words;
}
相關問題
- 1. 使用STL的單字母排序加密使用STL,cs106l
- 2. 使用帶unicode的STL字符串
- 3. 使用STL
- 4. 使用STL
- 5. 使用STL
- 6. 標記化字符串中使用STL
- 7. 使用STL對子字符串排序
- 8. 字謎發生器C++(不使用STL)
- 9. 使用STL遞歸?
- 10. 如何使用STL的slist?
- 11. 使用STL翻轉字符串中的字詞
- 12. STL按排序順序存儲數字
- 13. C++使用STL從字符串中刪除字符
- 14. 使用STL與COM接口
- 15. 向量和使用STL
- 16. 錯誤使用列表STL
- 17. 使用STL與Android NDK C++
- 18. 在STL中使用memcpy
- 19. 合併使用STL算法
- 20. 同時使用STL容器
- 21. 捲曲在C使用STL
- 22. 如何使用STL算法
- 23. C++ STL集合使用
- 24. 使用STL和鍊金術
- 25. sigsegv使用矢量stl
- 26. 在ATL內部使用STL
- 27. STL priority_queue參數
- 28. 使用成員函數作爲STL比較函數的bind()
- 29. 在C++中使用stl使用矩陣
- 30. 使用fread/fwrite作爲STL字符串。這是對的嗎?
[你嘗試過什麼(http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – 2012-03-05 08:00:00