I have this string:
https://insights.ubuntu.com/feed/">Canonical
How can I get, using a function, only:
https://insights.ubuntu.com/feed/
until the last slash (deleting ">Canonical
)?
Since the only thing that interests you is the string before the double quotes ( "
) you have a couple of options.
const std::string input = "https://insights.ubuntu.com/feed/\">Canonical";
std::string resultado;
std::copy_n(input.begin(), input.find('\"'), std::back_inserter(resultado));
With the above code you will copy the entire original string ( std::string resultado
) into the input
to the double quotes.
If instead of copying the content in another chain you prefer to modify the original string you can do it like this:
std::string input = "https://insights.ubuntu.com/feed/\">Canonical";
input.resize(input.find('\"'));
With the above code, the content of input
will be discarded after the double quotes leaving the string exactly as you need it.
Look at this possible solution, where we obtain the position of the word to be delimited and based on the constructor of the string class we copy from the zero position to the n position.
string filtrarString(string s,string delimitador)
{
int posDelimitador=s.find(delimitador);
return string(s,0,posDelimitador);
}
int main()
{
string url="https://insights.ubuntu.com/feed/>Canonical";
cout<<filtrarString(url,">Canonical")<<endl;
return 0;
}
If you can afford to compile with the C ++ 11 standard or later, you can use the regex
library to enter regular expressions.
std::regex e("<a\s[^>]*href=\"([^\"]*?)\"[^>]*>(.*?)</a>");
std::smatch m;
std::string s = "abcd<a href=\"https://insights.ubuntu.com/feed/\">Canonical</a>abcd";
std::regex_search(s,m,e);
if( m.size() > 1 )
std::cout << "Enlace encontrado: " << m[1] << '\n';
else
std::cout << "Enlace NO encontrado";
If not, you can always use boost (the code is quite similar) ... or you can even do the search manually.
The simplest thing in this case would be to locate the start and end quotes:
std::string s = "abcd<a href=\"https://insights.ubuntu.com/feed/\">Canonical</a>abcd";
int pos1, pos2;
pos1 = s.find('\"');
if( pos1 == std::string::npos )
pos1++;
else
pos2 = s.find('\"',pos1);
if( pos1 == std::string::npos || pos2 == std::string::npos )
std::cout << "Url no encontrada\n";
else
std::cout << s.substr(pos1,pos2-pos1);