#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "plus2net";
char str2='*';
printf("Original string : %s \n", str1);
strset(str1,str2);
printf("After strset() : %s",str1);
return 0;
}
The output of above code is here
Original string :plus2net
After strset() : ********
We can set all chars of a string to one input string by using strset()
string function.
strset(main_string, set_string);
Example: Custom Implementation of strset()
A user-defined function replaces each character in the string with a specific character.
#include <stdio.h>
void custom_strset(char *str, char ch) {
while (*str) {
*str = ch;
str++;
}
}
int main() {
char str[] = "Hello World!";
custom_strset(str, '*');
printf("Modified string: %s\n", str); // Output: *************
return 0;
}
Example: Handling Edge Cases (Null or Empty String)
The function handles null or empty strings safely.
#include <stdio.h>
void custom_strset(char *str, char ch) {
if (str == NULL) {
printf("String is NULL\n");
return;
}
while (*str) {
*str = ch;
str++;
}
}
int main() {
char *str = NULL;
custom_strset(str, '*'); // Output: String is NULL
char empty[] = "";
custom_strset(empty, '*');
printf("Modified empty string: %s\n", empty); // Output: (empty)
return 0;
}
Example: Replacing Special Characters in String
Shows how strset() can replace special characters and digits.
#include <stdio.h>
void custom_strset(char *str, char ch) {
while (*str) {
*str = ch;
str++;
}
}
int main() {
char str[] = "Hello, World! 123";
custom_strset(str, '#');
printf("Modified string: %s\n", str); // Output: ###############
return 0;
}