2010-07-26 165 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

相关问题