Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get String Between 2 Strings

Tags:

c++

string

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"?

like image 491
Ben Avatar asked Jul 26 '10 21:07

Ben


2 Answers

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)
like image 198
polygenelubricants Avatar answered Oct 20 '22 00:10

polygenelubricants


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

like image 29
RichardPowell Avatar answered Oct 19 '22 23:10

RichardPowell