strnset() is a non-standard extension that replaces up to the first n characters of a string. Portable C can implement the same operation with a bounded loop.
strnset() is not part of the ISO C standard library.strnset(string, '*', n); // non-standard
#include <stdio.h>
void set_first_n(char text[], char replacement, size_t n) {
size_t i = 0;
while (i < n && text[i] != '\0') {
text[i] = replacement;
i++;
}
}
int main(void) {
char text[] = "plus2net";
set_first_n(text, '*', 4);
printf("%s\n", text);
return 0;
}
Output
****2net
#include <stdio.h>
void set_first_n(char text[], char replacement, size_t n) {
size_t i = 0;
while (i < n && text[i] != '\0') {
text[i] = replacement;
i++;
}
}
int main(void) {
char text[] = "C";
set_first_n(text, '#', 5);
printf("%s\n", text);
return 0;
}
The loop stops at the null terminator, so it does not write beyond the string.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.