C++ has C-style string literals by default. For example,

#include <iostream>
 
int main(int argc, char const *argv[])
{
    std::cout << "Hello world".length();
    return 0;
}
 

If we compile this program, it results in error saying,

string_literals.cpp:5:32: error: request for member 'length' in '"Hello world"', which is of non-class type 'const char [12]'
    5 |     std::cout << "Hello world".length();

Info

I could not find a easier way to check type of string literal, so used .length() method on string 🙂.

From the error we can see the type of the string literal which is const char. This is C-style string literal.

std::string literal

We can also create std::string type. We need to suffix string with s as shown below.

#include <iostream>
 
int main(int argc, char const *argv[])
{
    using namespace std::string_literals;
 
    std::cout << "Hello world\n";
    std::cout << "Hello world"s.length() << "\n";
    return 0;
}

We shall following results when running the program.

Hello world
11

s requires namespace std::string_literals.

std::string_view literals

std::string_view literals can be created by suffixing string with sv as shown below.

#include <string_view>
#include "../helpers/stdout.h"
#include <iostream>
#include <typeinfo>
 
int main(int argc, char const *argv[])
{
 
    using namespace std::string_view_literals;
 
    print(typeid("Hello world"sv).name());
    return 0;
}

Compiling and running the program should give following result,

❯ g++-15 -ggdb -std=c++20 string_view.cpp ../helpers/stdout.cpp -o string-view
~/L/c++/strings
❯ ./string-view
St17basic_string_viewIcSt11char_traitsIcEE

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-stdstring/