C String strset() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
Extension / loop

What You’ll Learn

The strset() function replaces every character in a C-string with a single byte value, leaving the null terminator untouched. It is not ISO C standard—this tutorial shows the portable loop that works on every compiler.

01

Fill all

Up to null.

02

Same length

Keep '\0'.

03

In place

Modifies str.

04

Not ISO C

Extension.

05

vs strnset

First n only.

06

vs memset

Raw bytes.

Definition and Usage

strset stands for string set. Walking from index 0 until '\0', it writes the same character into each position. The string keeps the same length—only the visible symbols change.

Typical uses include masking an entire buffer for display, stamping a row of identical characters in legacy text formats, or quickly resetting working text before reuse (when you do not need to clear to empty).

💡
Beginner Tip

To make a string empty, set buf[0] = '\0'—do not fill with spaces unless you truly want a line of spaces. To zero every byte including padding in a struct, use memset, not strset.

📝 Syntax

Typical extension declaration:

C
char *strset(char *str, int c);

Portable alternative

C
char *str_set(char *s, char c) {
    char *start = s;
    while (*s != '\0') {
        *s++ = c;
    }
    return start;
}

Parameters

  • str — writable null-terminated string to modify.
  • c — fill byte (stored as char).

Return Value

  • Returns str (pointer to the modified buffer).

⚡ Quick Reference

BeforeCallAfterstrlen
"Hello, C!"str_set(s, '*')"*********"unchanged (9)
"ABC"str_set(s, '0')"000"3
""str_set(s, 'X')""0
null terminatornot overwrittenstill valid C-stringsame as before
Fill string
str_set(s, '*');

Portable

First n
strnset(s, c, n)

Partial

Raw fill
memset(buf, c, n)

Fixed n bytes

Empty
s[0] = '\0';

Clear text

Examples Gallery

Examples use the portable str_set helper so they compile on Linux, macOS, and Windows.

📚 Getting Started

Replace every visible character in a writable char array.

Example 1 — Fill With Asterisks

Turn "Hello, C Programming!" into a row of * characters.

C
#include <stdio.h>
#include <string.h>

char *str_set(char *s, char c) {
    char *start = s;
    while (*s != '\0') {
        *s++ = c;
    }
    return start;
}

int main(void) {
    char text[] = "Hello, C Programming!";

    printf("Before: %s (len=%zu)\n", text, strlen(text));
    str_set(text, '*');
    printf("After:  %s (len=%zu)\n", text, strlen(text));

    return 0;
}

How It Works

Twenty-one bytes change to '*'; the null at index 21 stays. strlen is unchanged because the terminator was not moved.

Example 2 — Fill With Zeros (Display Pattern)

Overwrite digits in a code string with '0'.

C
#include <stdio.h>

char *str_set(char *s, char c) {
    char *start = s;
    while (*s) {
        *s++ = c;
    }
    return start;
}

int main(void) {
    char code[] = "XY12";

    str_set(code, '0');

    printf("Code: %s\n", code);

    return 0;
}

How It Works

Every character becomes '0'. This is not the same as numeric zeroing memory—the string still reads as four ASCII zero digits.

📈 Practical Patterns

Masking, partial fill comparison, and edge cases.

Example 3 — Mask a Password for Logging

Replace every character before writing a log line (not for real security).

C
#include <stdio.h>

char *str_set(char *s, char c) {
    char *start = s;
    while (*s) {
        *s++ = c;
    }
    return start;
}

int main(void) {
    char secret[] = "MyPassword";

    str_set(secret, 'x');

    printf("Log: user entered [%s]\n", secret);

    return 0;
}

How It Works

Length stays 10, so the bracket shows ten x characters. For secrets, overwrite sensitive buffers with memset and avoid keeping passwords in plain char arrays.

Example 4 — strset() vs strnset()

Fill the whole string vs only the first three characters.

C
#include <stdio.h>
#include <string.h>

char *str_set(char *s, char c) {
    char *start = s;
    while (*s) { *s++ = c; }
    return start;
}

void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

int main(void) {
    char full[] = "Hello";
    char part[] = "Hello";

    str_set(full, '-');
    str_nset(part, '-', 3);

    printf("strset:  %s\n", full);
    printf("strnset: %s\n", part);

    return 0;
}

How It Works

strset touches every byte before '\0'. strnset(..., 3) changes only indices 0–2. Use partial fill when a prefix mask is enough.

Example 5 — Empty String Edge Case

When strlen is 0, the fill loop runs zero times.

C
#include <stdio.h>
#include <string.h>

char *str_set(char *s, char c) {
    char *start = s;
    while (*s) {
        *s++ = c;
    }
    return start;
}

int main(void) {
    char empty[] = "";

    str_set(empty, 'Z');

    printf("Empty after strset: [%s] len=%zu\n", empty, strlen(empty));

    return 0;
}

How It Works

The first byte is already '\0', so nothing changes. strset cannot lengthen a string—it only overwrites existing characters.

🚀 Common Use Cases

  • Visual masking — hide entire fields in debug output.
  • Placeholder rows — stamp repeated symbols in text UI prototypes.
  • Legacy record prep — uniform character fields before editing.
  • Teaching loops — walk a C-string until '\0'.
  • Reading old code — recognize Borland/MSVC extension calls.

🧠 How strset() Works

1

Start at str[0]

Save pointer for return value.

Init
2

While *s != '\0'

Write c and advance s.

Fill
3

Stop at null

Terminator unchanged; length preserved.

Stop
=

char* str

Uniform characters, valid C-string.

📝 Notes

  • Not part of ISO C—use the portable loop on GCC/Linux.
  • Does not change string length or the null terminator.
  • Requires a writable buffer; never pass string literals.
  • Not a secure way to erase secrets—use explicit clearing practices.
  • Pair with strnset() when only a prefix should change.

⚡ Optimization

Filling a string is O(n) in its length. For very long buffers, memset(str, c, strlen(str)) may be faster on some platforms because libraries optimize memset heavily—but only when you truly want every byte before the terminator replaced and the null left at the same index.

Conclusion

strset() overwrites every character in a C-string with one byte where the extension exists. Learn the portable while-loop, respect the null terminator, and choose strnset or memset when partial or raw fills fit better.

Next, learn strspn() to measure a leading run of accepted characters.

💡 Best Practices

✅ Do

  • Use a writable char[] buffer
  • Keep the portable while (*s) loop for cross-platform code
  • Use strnset when only part of the string should change
  • Verify strlen before and after when teaching
  • Clear strings with s[0]='\0' when you mean empty

❌ Don’t

  • Call strset on string literals
  • Assume strset is standard <string.h>
  • Expect the string to grow or shrink
  • Rely on strset for cryptographic secret wiping
  • Overwrite the null byte manually after strset

Key Takeaways

Knowledge Unlocked

Five things to remember about strset()

Use these points when filling an entire string in C.

5
Core concepts
📝 02

Same len

Keep '\0'.

Behavior
🔢 03

Extension

Not ISO C.

Portability
📈 04

vs strnset

First n.

Compare
💬 05

In place

Writable.

Safety

❓ Frequently Asked Questions

strset() replaces every character in a null-terminated string with the byte c (converted to char), stopping before the existing null terminator. The string length stays the same; only the visible characters change.
No. strset() is a compiler-specific extension (common on Microsoft and Borland toolchains). ISO C does not define it. Portable code uses a short while loop or memset on strlen(str) bytes only.
char* strset(char* str, int c); str must be a writable char array. c is the fill value, often written as a character literal like '*' or '0'.
strset() fills the entire string up to but not including '\0'. strnset(str, c, n) fills at most the first n characters (and stops early at '\0' if the string is shorter).
No. Typical strset implementations leave the terminating '\0' in place so the result remains a valid C-string with the same length as before.
No. String literals are read-only. strset modifies memory in place, so pass a writable char array such as char buf[] = "Hello";
Did you know?

The old reference incorrectly called strset() part of the C Standard Library. It is a vendor extension. Standard C gives you memset for byte fills and string functions like strcpy for text—know which tool matches C-strings vs raw memory.

Continue the String Functions Series

Fill entire strings with strset() concepts, then learn character spans with strspn().

Next: strspn() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful