Logo

Programming-Idioms

History of Idiom 169 > diff from v90 to v91

Edit summary for version 91 by programming-idioms.org:
[C++] Remove comments from snippet
↷

Version 90

2021-04-30, 23:08:58

Version 91

2021-05-23, 20:04:27

Idiom #169 String length

Assign to integer n the number of characters of string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.

Idiom #169 String length

Assign to integer n the number of characters of string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.

Variables
n,s
Variables
n,s
Extra Keywords
size characters chars number runes
Extra Keywords
size characters chars number runes
Code
//function
auto utf8len(std::string_view const& str) -> size_t
{
	std::setlocale(LC_ALL, "en_US.utf8");

	auto charCount = size_t{};
	auto size = size_t{};
	auto mb = std::mbstate_t{};

	while(size < str.length())
	{
		size += mbrlen(str.data() + size, str.length() - size, &mb);
		charCount += 1;
	}

	return charCount;
}

//use
constexpr auto s = "zß水🍌";
auto n = utf8len(s); // 4
Code
auto utf8len(std::string_view const& s) -> size_t
{
	std::setlocale(LC_ALL, "en_US.utf8");

	auto n = size_t{};
	auto size = size_t{};
	auto mb = std::mbstate_t{};

	while(size < s.length())
	{
		size += mbrlen(s.data() + size, s.length() - size, &mb);
		n += 1;
	}

	return n;
}
Demo URL
https://godbolt.org/z/16j5PcYar
Demo URL
https://godbolt.org/z/16j5PcYar