2016-06-13 8 views
-2

どのように2つの単語の間の文字列を返すのですか?たとえば: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?" 

私がやったことは、私の開始と終了の試合としての二つの文字列、startendを作成するプログラムを作成しました。私はそれらを探して正規表現の文字列を使い、その間の何かにマッチします(何もしません)。次に、regex_matchを使って式の一致部分を見つけ、一致した文字列として一致するものを設定します。詳細情報については

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

0

が良い場合されることがあります。あなたは5それぞれ4

あなたがこれを行うことができ、あなたの"START""STOP"の長さをするために知っていると仮定すると、

を使用でき
関連する問題