strset() and strnset() function in C language

strset() and strnset() string function is used to replace all the characters of a string by a specific character and replace n characters by a specific characters respectively. Here, in this article we will see some example C program using strset() and strnset() function.

Use of strset() function in C programming

The strset() function sets all the characters of a string to the given character we want to set. It is a non standard function and may not exist in standard library in C. See the syntax of strset() here.

// syntax of strset() string function in C

char *strset(char *String, int c);

Now, lets see a C program using strset() function.

// strset() function in C
#include<stdio.h>
#include<string.h>
int main(){
   char mainStr[20] = "Programmer";

   printf("Original string before strset() is : \n%s\n\n", mainStr);

   printf("After using strset() : \n%s\n",strset(mainStr,'p'));

   return 0;
}

Output of strset() function program

C strset() and strnset() function, strset() function in C

Use of strnset() function in C language

strnset() is also a built in string function in C which sets the first n characters of string to a specific character. But when n is greater than the length of string, then the length of string will be used instead of n. Syntax of strnset() function is given here.

// syntax of strnset() string function in C

char *strnset(const char *string, char ch, int n);

The program bellow will help you to know more about strnset() function in C.

// strnset() function in C
#include <stdio.h>
#include <string.h>

int main(){
  char myStr[] = "competitiveprogrammer";

  printf("Original String is : \n%s\n\n", myStr);

  printf("String after using strnset is : \n%s\n", strnset(myStr, '#', 5));

  return 0;
}

This program will give you the output like this.