2017-03-02 2 views
1

C++ newbie 여기에 내 제목이 무엇을 설명하려고하는지 잘 모르겠지만 기본적으로 특정 문자열 배열의 한 줄을 출력하려고합니다. 배열의 인덱스.배열의 특정 인덱스의 부분 문자열 출력

예를 들어 다음과 같습니다. myArray [2]가 문자열 배열의 세 번째 인덱스이고 각 단락을 개행 문자로 구분하여 전체 단락을 보유한다고 가정합니다.

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는 모든 배열의 * 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

멋진 템플릿, 고맙습니다. –

관련 문제