str1ng
str1ng

Reputation: 581

How do I find character in string and after that I extract the rest of string in C++

So my problem is next: I have youtube link entered as input, and I should print youtubeID as output.

So, perhaps I have this link: https://www.youtube.com/watch?v=szyKv63JB3s , I should print this "szyKv63JB3s", so I came to conclusion that I need to find that " = " in user inputed string and I should look to make new string called "ytID" or "result" and store youtubeID from the moment I find that " = " characther.

So I really don't have idea how should it be done... I mean I should go through string with for loop I guess, and after that I should store the part which will be called youtubeID, and I have problem there because I don't know how long is that link, I mean how much characthers it have, so I cannot really use for or while loops...

P.S This is not HOMEWORK, I just want to practice. :)

Upvotes: 0

Views: 190

Answers (2)

Aydan Haqverdili
Aydan Haqverdili

Reputation: 586

Just search for the character = as you mentioned in the question:

#include <iostream>
#include <string_view>


std::string_view extractYoutubeId(std::string_view const link) {
    auto const off = link.find('=');
    if (off == std::string_view::npos)
        return std::string_view{};
    return link.substr(off + 1);
}

int main() {
    auto const& link = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
    std::cout << extractYoutubeId(link);
}

Output: dQw4w9WgXcQ

Upvotes: 0

Etienne Salimbeni
Etienne Salimbeni

Reputation: 582

you should give a look at this post : Removing everything after character (and also character)

A solution could be as simple as :

theString.substr( theString.find('=') ) ;

Upvotes: 2

Related Questions