开发者

Get String Between 2 Strings

How can I get a string that is between two other declared strings, for example:

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

Source:

"832h0ufhu0sdf4[STRING1]I need this text here[STRING2]afyh0fhdfosdfndsf开发者_开发百科"

How can I get the "I need this text here"?


Since this is homework, only clues:

  • Find index1 of occurrence of String1
  • Find index2 of occurrence of String2
  • Substring from index1+lengthOf(String1) (inclusive) to index2 (exclusive) is what you need
    • Copy this to a result buffer if necessary (don't forget to null-terminate)


Might be a good case for std::regex, which is part of 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";

}

Prints:

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

What I did was create a program that creates two strings, start and end that serve as my start and end matches. I then use a regular expression string that will look for those, and match against anything in-between (including nothing). Then I use regex_match to find the matching part of the expression, and set matched as the matched string.

For more info, see http://en.cppreference.com/w/cpp/regex and http://en.cppreference.com/w/cpp/regex/regex_search


Use strstr http://www.cplusplus.com/reference/clibrary/cstring/strstr/ , with that function you will get 2 pointers, now you should compare them (if pointer1 < pointer2) if so, read all chars between them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜