strnset() – strset() — Set Characters in String
Format
#include <string.h>
char *strnset(char *string, int c, size_t n);
char *strset(char *string, int c);
Note: The
strnset
and strset
functions are available for C++ programs. They are available for C only when the program defines the __cplusplus__strings__ macro.Language Level
Extension
Threadsafe
Yes
Description
strnset
sets, at most, the first n characters of string to c (converted to a char). If n is greater than the length of string, the length of string is used in place of n. strset
sets all characters of string, except the ending null character (\0), to c (converted to a char). For both functions, the string is a null-terminated string.
Return Value
Both strset
and strnset
return a pointer to the altered string. There is no error return value.
Example
In this example,
strnset
sets not more than four characters of a string to the character 'x'. Then the strset
function changes any non-null characters of the string to the character 'k'. #include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "abcdefghi";
printf("This is the string: %s\n", str);
printf("This is the string after strnset: %s\n", strnset((char*)str, 'x', 4));
printf("This is the string after strset: %s\n", strset((char*)str, 'k'));
return 0;
}
The output should be: This is the string: abcdefghi
This is the string after strnset: xxxxefghi
This is the string after strset: kkkkkkkkk