2010-04-07 38 views
1

我只是試圖從文本文件中計算一行的左空白數目。 我一直在使用使用C++在文本文件中計算一行文本左側的空格

count(line.begin(), line.end(), ' '); 

但很明顯,包括單詞之間和右邊的所有空格向左,英寸 所以基本上我想要它做的是一旦它擊中一個非空間字符停止計數空白。

謝謝大家。

+1

什麼是'line'?一個'std :: string'? – 2010-04-07 17:21:25

+1

你在尋找非空白還是非空間? – Beta 2010-04-07 17:30:15

+0

@mmyers:我認爲這是一個合理的假設......儘管Nick Meyer的解決方案即使沒有該類型的成員函數也可以工作(所以它也適用於矢量)。 – 2010-04-07 17:55:28

回答

9

假設linestd::string,怎麼樣:

#include <algorithm> 
#include <cctype> 
#include <functional> 

std::string::const_iterator firstNonSpace = std::find_if(line.begin(), line.end(), 
    std::not1(std::ptr_fun<int,int>(isspace))); 
int count = std::distance(line.begin(), firstNonSpace); 
+0

+1:從技術上講,這是唯一正確的答案,因爲它確實可以實現真正的空白空間檢測。 – 2010-04-07 17:32:49

+0

@Martin約克:是的。它返回字符串的長度。 'find_if'返回失敗時的結束迭代器。 – 2010-04-07 17:47:48

+4

小挑剔:在這裏使用'std :: string :: const_iterator'會更普遍。計數空格不會修改字符串,並且在給定一個常量字符串的情況下應該可行。無論如何。 – sbi 2010-04-07 17:50:51

6

如何

line.find_first_not_of(' '); 

編輯: 如果它的所有空間:

unsigned int n = line.find_first_not_of(' '); 
if(n==s.npos) 
    n = line.length(); 
+0

if(n == -1)!!!!!!!! – 2010-04-07 17:37:00

+2

您應該使用line.npos而不是-1。根據您使用的平臺,該常數可能會有所不同。 – 2010-04-07 17:50:18

+0

@Billy ONeal:你說得對,謝謝;固定。 – Beta 2010-04-07 18:11:58

2
int i = 0; 
while (isspace(line[i++])) 
    ; 
int whitespaceCnt = i-1; 
0

是行的字符串?

在要std::string::find_first_not_of找到第一個非空白,然後就行了這樣的剩餘使用std::count這種情況下:

std::string::size_type firstNonSpace = line.find_first_not_of(' '); 
std::size_t result = std::count(line.begin()+(firstNonSpace==std::string::npos?0:firstNonSpace),line.end(),' '); 
+2

當你找到第一個非空間時,你不知道空間的大小嗎?爲什麼要調用'std :: count'? – 2010-04-07 17:51:00

6

找到的第一個非空白字符。

std::string   test = "  plop"; 
std::string::size_type find = test.find_first_not_of(" \t"); // Note: std::string::npos returned when all space. 

技術上不是白色空間(因爲其他字符也是白色空間)。
你想計算或去掉空白空間嗎?

如果您嘗試去除空白區域,那麼流操作符將自動執行。

std::stringstream testStream(test); 
std::string  word; 

testStream >> word; // white space stripped and first word loaded into 'word' 
+0

只是試圖計數,而不是剝離。謝謝 – user198470 2010-04-07 18:28:02