strset() is a non-standard extension that replaces every character of a string with one chosen character while preserving the terminating null character. The same behavior is easy to implement portably.
strset() is not an ISO C standard-library function.strset(string, '*'); // non-standard
#include <stdio.h>
void set_all_chars(char text[], char replacement) {
for (size_t i = 0; text[i] != '\0'; i++) {
text[i] = replacement;
}
}
int main(void) {
char text[] = "plus2net";
set_all_chars(text, '*');
printf("%s\n", text);
return 0;
}
Output
********
#include <stdio.h>
void set_all_chars(char text[], char replacement) {
for (size_t i = 0; text[i] != '\0'; i++) {
text[i] = replacement;
}
}
int main(void) {
char empty[] = "";
set_all_chars(empty, '#');
printf("Length remains zero: \"%s\"\n", empty);
return 0;
}
#include <stdio.h>
int set_all_chars(char *text, char replacement) {
if (text == NULL) {
return 0;
}
while (*text != '\0') {
*text = replacement;
text++;
}
return 1;
}
int main(void) {
char *text = NULL;
if (!set_all_chars(text, '*')) {
printf("String is NULL.\n");
}
return 0;
}
#include <stdio.h>
void set_all_chars(char text[], char replacement) {
for (size_t i = 0; text[i] != '\0'; i++) {
text[i] = replacement;
}
}
int main(void) {
char text[] = "Hello, World! 123";
set_all_chars(text, '#');
printf("%s\n", text);
return 0;
}
Output
#################
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.