Talk:Comparison of programming languages (string functions): Difference between revisions

Content deleted Content added
Cewbot (talk | contribs)
m Maintain {{WPBS}} and vital articles: 1 WikiProject template. Create {{WPBS}}. Keep majority rating "B" in {{WPBS}}. Remove 1 same rating as {{WPBS}} in {{WikiProject Computing}}.
 
Line 145:
 
It seems to me that this article, as useful as it is, is outside of Wikipedia's scope, in light of the principle that [[WP:NOTHOWTO|Wikipedia is not a how-to guide]], which is exactly what this article is. [[User:Largoplazo|Largoplazo]] ([[User talk:Largoplazo|talk]]) 10:00, 18 June 2020 (UTC)
 
== Mentioning strtok as C/C++ way of splitting strings ==
 
<code>strtok(char *restrict str, const char *restrict delim)</code>returns tokens (aka split strings). This is essentially what string.split does in most other languages, except it doesn't allocate memory to store array of tokens, instead just mutating original string (replacing delimiter with '\0')[https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c] and returning tokens in order of occurence, one by one.
Also it never returns empty tokens[https://en.cppreference.com/w/c/string/byte/strtok].
"Proper" implementation of split (using strtok) is something like:<syntaxhighlight lang=c>#include <stdlib.h>
#include <string.h>
struct stringArray {
size_t size;
char **strings;
};
struct stringArray splitString(char *restrict str, const char *restrict delim) {
char **strings = malloc(sizeof(char *));
if (strings == NULL)
abort();
char *token = strtok(str, delim);
size_t count = 0, allocated = 1;
while (token != NULL) {
if (allocated >= count) {
strings = realloc(strings, (allocated *= 2) * sizeof(char *)); // Doubling reallocation, to provide acceptable performance
if (strings == NULL)
abort();
}
strings[count++] = token;
token = strtok(NULL, delim);
}
if (allocated != count) {
strings = realloc(strings, count * sizeof(char *));
if (strings == NULL)
abort();
}
return (struct stringArray){count, strings};
}
</syntaxhighlight> [[Special:Contributions/5.189.81.197|5.189.81.197]] ([[User talk:5.189.81.197|talk]]) 15:25, 27 July 2024 (UTC)