[英]Count white spaces to the left of a line in a text file using C++
我只是想計算文本文件中一行的左空格數。 我一直在用
count( line.begin(), line.end(), ' ' );
但是很明顯,在單詞之間和右側,左側包括所有空白。 因此,基本上,我希望它執行的操作是一旦它碰到一個非空格字符,就停止計數空白。
感謝大家。
假設line
是一個std::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);
怎么樣
line.find_first_not_of(' ');
編輯:萬一所有的空間:
unsigned int n = line.find_first_not_of(' ');
if(n==s.npos)
n = line.length();
查找第一個非空白字符。
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'
int i = 0;
while ( isspace( line[i++] ) )
;
int whitespaceCnt = i-1;
行是字符串嗎?
在這種情況下,您想要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(),' ');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.