How can I get the byte size of std::wstring?
Asked Answered
T

4

22

I am using std::wstring as my Unicode style string. Now I want to get the byte size of a wstring. If I use size() method of wstring, I just get the total number of chars in my wstring. But the byte should be size() * 2. Is there an official way to get this byte size? I don't want to use size() * 2 in my program.....

I want to use in RegSetValueExW as last parameter.

Thyestes answered 14/2, 2012 at 14:36 Comment(0)
C
25

Use str.size() * sizeof(wchar_t) or equivalent.

In fact, I can't think of any other platform besides Windows that has 2-byte wchar_t, 4 bytes is far more common.

Coadunate answered 14/2, 2012 at 14:40 Comment(1)
If you're setting a REG_SZ using RegSetValueExW, you'll want to also add a character for the null terminator: (str.size() + 1) * sizeof(wchar_t)Deboradeborah
N
9

Why not :

( str.size() * sizeof(wchar_t) ) ;

Or :

( str.size() * sizeof(std::wstring::traits_type::char_type) ) ;
Negro answered 14/2, 2012 at 14:48 Comment(2)
sizeof(char) is guaranteed to be 1, no need to divide by it.Tillett
Yes in any standard compliant compiler sizeof(char) == 1, I edited my answer.Negro
A
3
std::wstring s = L"Howdy, world!";
//...
std::size_t bytes_count = s.size() * sizeof s[0];
Afghanistan answered 22/12, 2015 at 22:10 Comment(0)
M
-3

You can use wcslen function

MSDN link: http://msdn.microsoft.com/en-us/library/78zh94ax.aspx

Linux: http://linux.die.net/man/3/wcslen

Mylonite answered 15/2, 2012 at 16:24 Comment(1)
That returns number of chars, not the number of bytes, and requires a C-Style pointer, not a std::w/string.Forwent

© 2022 - 2024 — McMap. All rights reserved.