2013-02-24 16 views
0

我想檢查一行是否有10個字。我做的方法是,我複製一行,並逐個提取並遞增計數器,如果它是10,我操縱該行。但我覺得這是非常低效的,因爲我必須爲每一行都做這件事,並且大多數行都是10個字。所以我正在尋找一種更有效的方法來做到這一點。任何更快的方法來計算istringstream中的字符串數

while(getline(ifs, line)){ 
     istringstream iss (line); 
     int s_counter = 0; 
     istringstream iss_copy = iss; //create a copy to test if there are 10 strings in a iss 
     string s; 
     while (iss_copy >> s){ 
      ++s_counter; 
     } 
     if (s_counter == 10){ 
      while(iss>>word){ 
       ...//manipuate each word     
      } 
     } 
    } 
+0

只能算一行空格嗎? – billz 2013-02-24 23:36:52

+1

我認爲在考慮代碼是否應該優化時應該考慮到這種感覺。 – Jack 2013-02-24 23:37:11

+0

@billz我想過了,但這不是基本上相同的想法嗎? – HoKy22 2013-02-24 23:42:11

回答

0

我的人做這種方式:

int main() 
{ 
    std::string s1("hi hi hi hi //blah"); 
    size_t pos = s1.find('/'); 
    std::cout << std::count(s1.begin(), s1.begin()+pos, ' ') << std::endl; 
    return 0; 
} 

OR

int countSpace(const std::string& s) 
{ 
    int count = 0; 

    for(size_t i=0; i<s.size()-1; i++) 
    { 
    if (s[i] == ' ') 
    { 
     count++; 
    } 
    if (s[i+1] == '/') 
    { 
     return count; 
    } 
    } 
    return count; 
} 


int main() 
{ 
    std::string s1("hi hi hi hi //blah"); 
    countSpace(s1); 
    return 0; 
} 
+0

我喜歡STL算法的方式..它應該比你提供的其他方式更快嗎? – HoKy22 2013-02-25 00:32:08

+0

也許STL一個更慢,因爲它確實發現了兩次。 – billz 2013-02-25 00:33:35

0

你可以更有效地使用STL算法。

template<typename charT> 
struct CntSpaceFunctor { 
    bool isEnd ; 
    std::size_t value ; 
    CntSpaceFunctor() : isEnd(false),value(0) {} 

    inline void operator()(charT ch) const { 
     if(ch == charT(' ') && !isEnd) ++value ; 
     else if(ch == charT('/'))  isEnd = true ; 
     else ; 
    } 
}; 
int countSpace(const string& str) { 
    CntSpaceFunctor<char> result ; 
    return for_each(str.begin() , str.end() , result).value ; 
} 
相關問題