2016-07-11 30 views
0

我想知道如何將一個行尾字符'\ n'與一個字符串進行比較。 我真的不想使用getline函數,因爲它對我不方便。我們如何將一個行尾字符' n'與一個字符串進行比較?

我的目的是在每次到達行尾字符'\ n'時增加行數,以便每次我的文件讀取一個單詞時,它都會輸出它所在的行號。

例如,如果字「藍色」是在第2行的屏幕將輸出線2 或如果詞「常用」是在管線4中的屏幕將輸出線4

感謝, 這是我第一次使用該網站。

+0

我不知道「比較[字符]和字符串」是什麼意思。 – immibis

+1

您是否正在嘗試製作一個程序來查找文件中的單詞,並告訴單詞在哪一行? – Olathe

+0

您是從輸入流中讀取數據還是僅僅通過一個類似'for(int i = 0; i

回答

0

從我的理解,下面的函數是你在找什麼。它會計算出\n的出現次數並返回計數。你可以把它重構輸出每發現一個新行時間的行數(請參見下面的註釋)

int count_new_lines(string s) { 
    int count = 0; 

    for (int i = 0; i < s.size(); i++) 
     if (s[i] == '\n') 
     { 
      count++; 
      //Output to file the number of the line 
     } 

    return count; 
} 

編輯: 既然你需要經過串的整體向量,並假設你不需要在所有矢量裏面的字符串對象來算行號,這是你應該做的事情:

int count_new_lines(vector<string> stringVector) { 
    int count = 0; 
    for (int strings = 0; strings < stringVector.size(); strings++) 
    { 
     string s = stringVector[strings]; 
     for (int i = 0; i < s.size(); i++) 
      if (s[i] == '\n') 
      { 
      count++; 
      //Output to file the number of the line 
      } 
    } 
    return count; 
} 

這將那矢量內返回所有的字符串對象行的總數你的。爲了獲得更好的性能和其他好處,可考慮將向量作爲參考或指針傳遞,但這些是更高級的主題。

以供將來參考 - 該功能會使用引用和指針,而不是複製對象,如以下行受益非淺:

string s = stringVector[strings]; 
+0

Opps!對不起,字符串類型實際上是矢量。 – Stephan

+0

我已經在你的代碼中使用了部分代碼,但它不起作用。我認爲這是因爲矢量類型 – Stephan

+0

是啊經歷矢量將是一個稍微不同的故事。那麼每個字符串元素在std :: vector中代表什麼?即每個字符串是一個文字,一行,一個段落還是文件的全部內容? –

0

要查找的字符出現的次數在一個字符串,我們可以使用

size_t count = std::count(str.begin(), str.end(), '\n'); 

例如

#include <algorithm> 
#include <string> 
#include <iostream> 

int main() { 
    std::string str("hello\nworld\n"); 
    std::cout << std::count(str.begin(), str.end(), '\n'); 
} 

http://ideone.com/mxRpKd

根據另一種回答您的意見,你想跨越串的向量來獲得總數:

size_t vec_char_count(const std::vector<std::string>& vec, char c) { 
    size_t count = 0; 
    for (const auto& str : vec) { 
     count += std::count(str.begin(), str.end(), c); 
    } 
    return count; 
} 

演示:http://ideone.com/DAkWRj

+0

我會使用'for(const auto&str:vec)',因爲我們不想修改向量中的字符串。除此之外,這是我可能會用到的。 – Lehu

相關問題