Logo

Programming-Idioms

History of Idiom 169 > diff from v89 to v90

Edit summary for version 90 by Steranoid:
New C++ implementation by user [Steranoid]
↷

Version 89

2021-03-24, 21:46:14

Version 90

2021-04-30, 23:08:58

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
Demo URL
https://godbolt.org/z/16j5PcYar