2010-07-26 190 views
4

之間,我可以得到一個字符串,它是其他兩個之間如何聲明字符串,例如:獲取字符串2個字符串

String 1 = "[STRING1]" 
String 2 = "[STRING2]" 

來源:

"832h0ufhu0sdf4[STRING1]I need this text here[STRING2]afyh0fhdfosdfndsf" 

我怎樣才能獲得"I need this text here"

回答

7

因爲這是家庭作業,只有線索:

  • 找到String1
  • 發生index1查找String2
  • 子串出現的index2index1+lengthOf(String1)(含)至index2(獨家)就是你需要
    • 如果需要,將其複製到結果緩衝區(不要僞造噸爲null-終止)
0

使用strstrhttp://www.cplusplus.com/reference/clibrary/cstring/strstr/,與該功能你會得到2個球,現在你應該對它們進行比較(如果指針1 <指針2)如果是這樣,閱讀它們之間的所有chars

+0

如果什麼'pointer1'是'NULL',但'pointer2'不是-'NULL'? – dreamlax 2010-07-26 22:51:14

+0

該解決方案可以解決很多問題。 「[String2] XX [String1] YY [String2]」值得思考。 – 2010-07-27 06:49:14

2

可能是STD良好的情況下::正則表達式,其是C++ 11的一部分。

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

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

    auto start = "\\[STRING1\\]"s; 
    auto end = "\\[STRING2\\]"s; 

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

    auto example = "832h0ufhu0sdf4[STRING1]I need this text here[STRING2]afyh0fhdfosdfndsf"s; 

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

    if (std::regex_search(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: "832h0ufhu0sdf4[STRING1]I need this text here[STRING2]afyh0fhdfosdfndsf" 
matched: "I need this text here" 

我所做的就是創建一個用於創建兩個字符串,並開始充當我的開始和結束的比賽結束程序。然後我使用一個正則表達式字符串來查找這些字符串,並匹配中間的任何內容(不包括任何內容)。然後我使用regex_match來查找表達式的匹配部分,並將匹配的字符串設置爲匹配。

欲瞭解更多信息,請參閱http://en.cppreference.com/w/cpp/regexhttp://en.cppreference.com/w/cpp/regex/regex_search