2017-03-02 5 views
1

C++ newbieここでは、私のタイトルが私が完璧にしようとしていることを記述しているかどうかはわかりませんが、基本的には、その配列のインデックス配列の特定のインデックスの部分文字列を出力する

たとえば、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." 

文字列配列の3番目のインデックスに保持されているコンテンツの最初の文のみを出力したいとします。

Desired output: This is just an example. 

これまでのところ、私は基本的なを使用して、代わりに一つの文章の段落全体を出力することができました:

cout << myArray[2] << endl; 

しかし、明らかに、これは正しくありません。私はこれを行うための最善の方法は何らかの方法で改行文字を使用することだと仮定していますが、それについてどうやって行くのかは分かりません。私はおそらく、元の配列インデックスに保持されている段落の文を各インデックスに保持する新しい一時配列に配列をコピーできると思っていましたが、問題があまりに複雑になっているようです。

私はまた、文字列配列をベクトルにコピーしようとしましたが、それは私の混乱を助けるようには見えませんでした。

+0

std :: basic_string :: find、std :: basic_string :: substringを見てください – Ceros

+1

'std :: find()'を使って最初の '\ n ''文字の位置を見つけて'std :: string :: substr()'を長さとします。 –

+0

実際にインデックス2は、任意の配列の* 3番目の要素です。 –

答えて

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

素敵なテンプレート、ありがとう –

関連する問題