2 ms·
It should be 4 as long as you count the grapheme clusters which is what e.g. Swift does (hence String#count being O(n)). In Javascript, you can get the same in
by masklinn 3y ago
It should be 4 as long as you count the grapheme clusters which is what e.g. Swift does (hence String#count being O(n)).
In Javascript, you can get the same information through Intl.Segmenter, segments by grapheme cluster by default.
- danbruc 3y agoYou could also have it in O(1), just store and maintain it as you usually store the length in bytes or code units. If you had all your string operations like substring work with grapheme clusters by default, which might arguably make sense quite often, then that could actually be a good decision. It might even make sense to maintain a list with pointers to each grapheme cluster or of all the grapheme cluster lengths together with the actual string data. Or maybe not, would probably depend heavily on the workload.