2017-03-02 138 views
1

這裏是C++新手,我不確定我的標題是否描述了我想要做的完美,但基本上我試圖輸出一行字符串數組該數組的索引。輸出數組中某個索引的部分字符串

例如:說myArray [2]是字符串數組的第3個索引,它包含整個段落,每個句子用換行符分隔。

contents of myArray[2]: "This is just an example. 
         This is the 2nd sentence in the paragraph. 
         This is the 3rd sentence in the paragraph." 

我想只輸出保存在字符串數組的第三個索引中的內容的第一句。

Desired output: This is just an example. 

到目前爲止,我只能夠輸出全款,而不是一個句子,用基本的:

cout << myArray[2] << endl; 

但很明顯,這是不正確的。我假設最好的辦法是以某種方式使用換行符,但我不知道如何去做。我以爲我可以將數組複製到一個新的臨時數組中,該數組可以在每個索引中保存原始數組索引中段落的句子,但是這似乎使得問題變得更加複雜。

我也嘗試將字符串數組複製到一個向量中,但這似乎並沒有幫助我的困惑。

+0

看看std :: basic_string :: find,std :: basic_string :: substring – Ceros

+1

使用'std :: find()'來查找第1個'\ n'字符的位置,並使用它與'std :: string :: substr()'作爲長度。 –

+0

其實索引2是任何數組中的* third *元素。 –

回答

2

您可以沿着這些路線

size_t end1stSentencePos = myArray[2].find('\n'); 
std::string firstSentence = end1stSentencePos != std::string::npos? 
    myArray[2].substr(0,end1stSentencePos) : 
    myArray[2]; 
cout << firstSentence << endl; 

這裏是std::string::find()std::string::substr()參考文檔做一些事情。

+0

非常感謝。 –

1

下面是對您的問題的一般解決方案。

std::string findSentence(
    unsigned const stringIndex, 
    unsigned const sentenceIndex, 
    std::vector<std::string> const& stringArray, 
    char const delimiter = '\n') 
{ 
    auto result = std::string{ "" }; 

    // If the string index is valid 
    if(stringIndex < stringArray.size()) 
    { 
     auto index = unsigned{ 0 }; 
     auto posStart = std::string::size_type{ 0 }; 
     auto posEnd = stringArray[stringIndex].find(delimiter); 

     // Attempt to find the specified sentence 
     while((posEnd != std::string::npos) && (index < sentenceIndex)) 
     { 
      posStart = posEnd + 1; 
      posEnd = stringArray[stringIndex].find(delimiter, posStart); 
      index++; 
     } 

     // If the sentence was found, retrieve the substring. 
     if(index == sentenceIndex) 
     { 
      result = stringArray[stringIndex].substr(posStart, (posEnd - posStart)); 
     } 
    } 

    return result; 
} 

其中,

  • stringIndex是字符串的搜索索引。
  • sentenceIndex是要檢索的句子的索引。
  • stringArray是包含所有字符串的數組(我使用了vector)。
  • delimiter是指定句子結尾的字符(默認爲\n)。

這是安全的,如果指定了無效的字符串或句子索引,它將返回一個空字符串。

查看完整示例here

+0

精彩模板,謝謝 –