strnset() and Portable Partial String Replacement

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.

Portability: strnset() is not part of the ISO C standard library.

Legacy Syntax Top ↑

strnset(string, '*', n);  // non-standard

Portable Replacement Top ↑

#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

When n Is Longer Than the String Top ↑

#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.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer