strnset() function in C

The strnset() function is a builtin function in C and it sets the first n characters of a string to a given character. If n is greater than the length of string, the length of string is used in place of n.

Syntax:

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

Parameters:

  • str: This is the original string in which some character are replaced by a given character.
  • ch: ch represents the given character.
  • n: n represents the number of character which is replaced by the given character.

Return Value: It returns the modified string obtained after replacing the first n characters of the given string str.

Below programs illustrate the strnset() function in C:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate 
// the strnset() function
  
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[] = "GeeksforGeeks";
      
    printf("Original String: %s\n", str);
      
    // First 5 character of string str
    // replaced by character '*'
    printf("Modified String: %s\n", strnset(str, '*', 5));
      
    return 0;
}

chevron_right


Output:

Original String: GeeksforGeeks
Modified String: *****forGeeks

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate 
// the strnset() function
  
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[] = "Computer Science";
      
    printf("Original String: %s\n", str);
      
    // First 5 character of string str
    // replaced by character '*'
    printf("Modified String: %s\n", strnset(str, '*', 5));
      
    return 0;
}

chevron_right


Output:

Original String: Computer Science
Modified String: *****ter Science

Note: The strnset() function is not a part of the standard C library and thus might not run on the online compilers.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.