Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::wstring length

What is the result of std::wstring.length() function, the length in wchar_t(s) or the length in symbols? And why?

TCHAR r2[3];
r2[0] = 0xD834;  // D834, DD1E - musical G clef
r2[1] = 0xDD1E;  //
r2[2] = 0x0000;  // '/0'

std::wstring r = r2;

std::cout << "capacity: " << r.capacity() << std::endl;
std::cout << "length: "   << r.length()   << std::endl;
std::cout << "size: "     << r.size()     << std::endl;
std::cout << "max_size: " << r.max_size() << std::endl;

Output>

capacity: 351
length: 2
size: 2
max_size: 2147483646
like image 933
Julian Popov Avatar asked Nov 15 '10 11:11

Julian Popov


People also ask

How do you measure Wstring length?

std::wstring::size() returns the number of wide-char elements in the string.

What is a std::wstring?

The standard library contains many useful classes -- but perhaps the most useful is std::string. std::string (and std::wstring) is a string class that provides many operations to assign, compare, and modify strings.

How do I convert Wstring to Wchar?

There is no way to convert wstring to wchar_t* but you can convert it to const wchar_t* which is what answer by K. Kirsz says. This is by design because you can access a const pointer but you shouldn't manipulate the pointer.

Does std :: string store size?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation. To achieve this libc++ uses a neat trick: the size of the string is not saved as-is but rather in a special way: if the string is short (< 23 bytes) then it stores size() * 2 .


1 Answers

std::wstring::size() returns the number of wide-char elements in the string. This is not the same as the number of characters (as you correctly noticed).

Unfortunately, the std::basic_string template (and thus its instantiations, such as std::string and std::wstring) is encoding-agnostic. In this sense, it is actually just a template for a string of bytes and not a string of characters.

like image 82
Frerich Raabe Avatar answered Sep 17 '22 22:09

Frerich Raabe