Name n3664, alx-0026r4 - add strchrcnt(), strchrscnt(), wcschrcnt(), wcschrscnt() Principles - Codify existing practice to address evident deficiencies. - Enable secure programming Category Standardize common string APIs Author Alejandro Colomar History r0 (2025-06-14): - Initial draft. r1 (2025-06-26): - s/Description/Rationale/ r2 (2025-06-29; n3618): - Clarify that the null byte is also searched. r3 (2025-07-03): - tfix - Don't repeat the name of the function within the description. r4 (2025-07-27; n3664): - Add note about DoS. Rationale It is a common operation to count the number of occurrences of one character or a set of characters. Several projects define functions for this purpose: strchrcnt() for one character, and strchrscnt() for a set of characters. Let's provide a standard API, which will avoid loops that are prone to off-by-one bugs. DoS concerns While one may be concerned that these APIs may promote DoS attacks by searching in a loop within a loop, these APIs are designed to be used with (short) string literals as the second argument. It would only be a concern if the second argument can be controlled by a user, but that would be unusual. Design choices - strchrscnt() would be enough, but strchrcnt() would be more efficient for the common case of searching just one character. So, let's provide both. Proposed wording Based on N3550. 7.28 String handling ## New section after 7.28.5 ("Search functions") +7.28.5+1 Count functions +7.28.5+1.1 The strchrcnt function + +Synopsis +1 #include + size_t strchrcnt(const char *s, char c); + +Description +2 This function counts + the number of occurrences of c + in the string pointed to by s. + The terminating null character + is considered to be part of the string. + +Returns +3 This function returns + the number of occurrences of c + in the string pointed to by s. + +7.28.5+1.2 The strchrscnt function + +Synopsis +1 #include + size_t strchrscnt(const char *s, const char *chrs); + +Description +2 This function counts + the number of occurrences of characters + from the string pointed to by chrs + in the string pointed to by s. + +Returns +3 This function returns + the number of occurrences of characters + from the string pointed to by chrs + in the string pointed to by s. 7.33.4 General wide string utilities ## New section after 7.33.4.6 ("Wide string search functions") +7.33.4.6+1 Wide string count functions +7.33.4.6+1.1 The wcschrcnt function + +Synopsis +1 #include + size_t wcschrcnt(const wchar_t *s, wchar_t c); + +Description +2 This function + is equivalent to + strchrcnt, + except that it handles wide characters. + +7.33.4.6+1.2 The wcschrscnt function + +Synopsis +1 #include + size_t wcschrscnt(const wchar_t *s, const wchar_t *chrs); + +Description +2 This function + is equivalent to + strchrscnt, + except that it handles wide characters.