#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "plus2net";
char str2='*';
printf("Original string : %s \n", str1);
strnset(str1,str2,4);
printf("After strset() : %s",str1);
return 0;
}
The output of above code is here
Original string :plus2net
After strnset() : ****2net
We can set part of the chars of a string to one input string by using strnset()
string function.
strnset(main_string, set_string,n);
Example: Custom Implementation of strnset()
#include <stdio.h>
void custom_strnset(char *str, char ch, int n) {
for (int i = 0; i < n && str[i] != '\0'; i++) {
str[i] = ch;
}
}
int main() {
char str[] = "Hello World!";
custom_strnset(str, '*', 5);
printf("Modified string: %s\n", str); // Output: ***** World!
return 0;
}
Output
Modified string: ***** World!
Example: Handling Empty Strings and Shorter Length
#include <stdio.h>
void custom_strnset(char *str, char ch, int n) {
for (int i = 0; i < n && str[i] != '\0'; i++) {
str[i] = ch;
}
}
int main() {
char empty_str[] = "";
custom_strnset(empty_str, '*', 3);
printf("Empty string result: %s\n", empty_str); // Output: (empty)
char short_str[] = "Hi";
custom_strnset(short_str, '*', 5); // Attempting to set more than the string length
printf("Short string result: %s\n", short_str); // Output: **
return 0;
}
Output
Empty string result:
Short string result: **