C++17 How to search into a string using string::string_view::substr as the 'string' to be searched?

213 views
Skip to first unread message

teco...@gmail.com

unread,
Jun 21, 2017, 4:45:44 AM6/21/17
to ISO C++ Standard - Discussion
Using string_view to search into string is very efficient, specially if you want to extract a substr without create a new string object like std::string::substr does.

Then:

    string sTest(".......9999.......");
    string_view vsTest = sTest;
    cout << vsTest.substring(7,4);     //That is more efficient then
    cout <<  sTest.substring(7,4);     //that one

On C++11 I usually wrote a search of substring into a string like that

    string s_Sub("+++++++9999+++++++");
    string sTest(".......9999.......");
    cout << (sTest.find(s_Sub.substr(7,4))) << '\t';

I thought the natural step to C++17 is:

    string s_Sub("+++++++9999+++++++");
    string sTest(".......9999.......");
    string_view vsSub = s_Sub;
    cout << (sTest.find(vsSub.substr(7,4))) << '\t';

But surprisingly it doesn't compile on gcc 5.4.0.

error: no matching function for call to ‘std::__cxx11::basic_string<char>::find(std::experimental::fundamentals_v1::basic_string_view<char>)’|

That is because my compiler or because std::string::find won't be ready to receive a string_view as parameter?

In my opinion, create a new string_view object to every string (sTest in this case) is not the best practice despite it is cheap because because it seems totally unnecessary.

Nicol Bolas

unread,
Jun 21, 2017, 9:30:15 AM6/21/17
to ISO C++ Standard - Discussion, teco...@gmail.com
GCC 5.4 is hardly the current version of GCC; it doesn't claim C++17 support. cppreference.com shows that the function in question does have such an overload in C++17.

d25f...@outlook.com

unread,
Jun 21, 2017, 9:32:24 AM6/21/17
to std-dis...@isocpp.org

> That is because my compiler or because std::string::find won't be ready to receive a string_view as parameter?

It was not until GCC 7 that libstdc++ implemented std::basic_string::find(std::basic_string_view) (p0254r2): https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.201z
Reply all
Reply to author
Forward
0 new messages