String Views

wstring_view vs string_view

How does std::wstring_view differ from std::string_view?

Abstract art representing computer programming

std::wstring_view and std::string_view are similar types in C++, both introduced to provide a lightweight, read-only view of a string.

The primary difference between the two lies in the type of characters they handle.

  • std::string_view is an alias for std::basic_string_view<char>. It works with narrow (8-bit) character strings.
  • std::wstring_view is an alias for std::basic_string_view<wchar_t>. It works with wide (typically 16-bit or 32-bit) character strings.

Here’s a simple comparison:

#include <iostream>
#include <string_view>
#include <string>
#include <cwchar>

int main() {
  std::string_view sv{"Hello, world"};
  std::wstring_view wsv{L"Hello, wide world"};

  std::cout << sv << '\n';
  std::wcout << wsv;
}
Hello, world
Hello, wide world

Use std::wstring_view when you are dealing with wide-character strings, which are often used for Unicode or platform-specific text representations requiring more than one byte per character.

In contrast, std::string_view is used for narrow-character strings, which are more common in ASCII or UTF-8 encoded text.

Choosing between these types depends on the nature of the text data you are handling. For most internationalized applications, std::wstring_view can be essential for proper character representation and manipulation.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved