Ondrashek
Ondrashek

Reputation: 139

C++ get value from string

I need get value from string. I have this piece of HTML:

<input type="hidden" name="wtkn" value="56e45dbe_wNIT/DcufUPvZOL33jmkyqGpKxw=">

And in C++ this code:

  static string pat4 = " name=\"wtkn\"";
  string::size_type wtkn;
  if ((wtkn = l.find(pat4)) != string::npos)
  {   
    l.erase(0,401);
    l.erase(37,43);   
        string token = l; 

    return token;      

  } 

So I need this from HTML: 56e45dbe_wNIT/DcufUPvZOL33jmkyqGpKxw= But this string is about 37 or 38 chars. So erase thing is not the best option.

Upvotes: 0

Views: 7129

Answers (2)

James Adkison
James Adkison

Reputation: 9602

Using just builtin C++ objects and functions you could do something like the following:

Example Code

#include <iostream>
#include <string>

std::string getValue(const std::string &html)
{
    static const std::string VALUE = "value";
    static const char DOUBLE_QUOTE = '"';

    std::string result;

    std::size_t pos = html.find(VALUE);
    if (pos != std::string::npos)
    {
        std::size_t beg = html.find_first_of(DOUBLE_QUOTE, pos);

        if (beg != std::string::npos)
        {
            std::size_t end = html.find_first_of(DOUBLE_QUOTE, beg + 1);

            if (end != std::string::npos)
            {
                result = html.substr(beg + 1, end - beg - 1);
            }
        }
    }

    return result;
}

int main()
{
    std::string html = "<input type=\"hidden\" name=\"wtkn\" value=\"56e45dbe_wNIT/DcufUPvZOL33jmkyqGpKxw=\">";
    std::cout << "HTML: " << html << "\n";
    std::cout << "value: " << getValue(html) << "\n";
    return 0;
}

Example Output

HTML: <input type="hidden" name="wtkn" value="56e45dbe_wNIT/DcufUPvZOL33jmkyqGpKxw=">
value: 56e45dbe_wNIT/DcufUPvZOL33jmkyqGpKxw=

Live Example


Note: Additional error checking may be required for a robust solution. This example implementation also has some preconditions (e.g., contains the value keyword followed by the desired text between opening and closing double quotes).

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 148870

As the requirement is simple you can parse it with just the standard library string methods. You can search for " value=" with find (the same you used for " name=\"wtkn\"" and from there search for next double quote ("):

const string deb = " value=\";
size_t deb_pos = l.find(deb);
if (deb_pos == string::npos) throw exception("deb not found");
deb_pos += deb.size();
size_t end_pos = l.find('"', deb_pos);
if (end_pos == string::npos) throw exception("end not found");
string token = l.substr(deb_pos, end_pos);

It would break if there are extra white spaces around the equal sign, or if there is a quoted double quote (\") in the string, but if you can be sure that it should not happen, that could be enough (beware: untested)

Upvotes: 1

Related Questions