2016-06-13 2 views
-2

어떻게 두 단어 사이에서 문자열을 반환합니까? 예를 들어 :두 단어 사이에서 문자열 가져 오기?

STARThello how are you doing today?END

출력은 다음과 같습니다

hello how are you doing today?

나는 항상 내가 그렇게 할 수있을 것입니다 방법에 대한 호기심이있었습니다.

std::string str = "STARThello how are you doing today?END"; 
const int startSize = 5; //or perharps something like startString.size() 
const int endSize = 4; //or perharps something like stopString.size() 
const int countSize = str.size() - (startSize + endSize); 

std::string substring = str.substr(startSize, countSize); 
+0

은 문자열의 길이는 고정되어 참조? 'START'와'END'라는 단어가 고정되어 있습니까? 아니면'BEGIN'과'END'와 같은 다른 단어도 될 수 있습니까? –

+0

아니요. START는 문자열이 시작되는 위치이고 END는 문자열이 끝나는 위치입니다. – okay14

+0

아, 물론! 그것도 작동합니다. – okay14

답변

0

std::string::substr

std :: regex는 C++ 11의 일부입니다.

#include <iostream> 
#include <string> 
#include <regex> 

int main() 
{ 
    using namespace std::string_literals; 

    auto start = "START"s; 
    auto end = "END"s; 

    std::regex base_regex(start + "(.*)" + end); 

    auto example = "STARThello how are you doing today?END"s; 

    std::smatch base_match; 
    std::string matched; 

    if (std::regex_match(example, base_match, base_regex)) { 
     // The first sub_match is the whole string; the next 
     // sub_match is the first parenthesized expression. 
     if (base_match.size() == 2) { 
      matched = base_match[1].str(); 
     } 
    } 
    std::cout << "example: \""<<example << "\"\n"; 
    std::cout << "matched: \""<<matched << "\"\n"; 

} 

인쇄 :

example: "STARThello how are you doing today?END" 
matched: "hello how are you doing today?" 

은 내가 한 일은 두 개의 문자열을 생성하는 프로그램을 작성했다 start 내 시작과 끝이 일치 역할을 end. 그런 다음 정규 표현식 문자열을 사용하여 그 문자열을 찾아서 아무것도 포함하지 않는 모든 문자열과 일치시킵니다. 그런 다음 regex_match를 사용하여 표현식의 일치하는 부분을 찾고 일치하는 문자열로 일치를 설정합니다. 더 많은 정보를 들어

http://en.cppreference.com/w/cpp/regexhttp://en.cppreference.com/w/cpp/regex/regex_search

0

이 좋은 경우 수 있습니다 : 당신이 5 각각 4,

이 작업을 수행 할 수 있습니다 "START""STOP"의 길이를 할 알고 가정

사용할 수
관련 문제