Manipulating Strings in C: Custom Functions for Copying and Selecting
Custom C Function: Copy and Select Characters with my_strcpy and my_strchr
To design a function using my_strcpy and using my_strchr to select a given character in a given string in C, we can use the following steps:
Create a function prototype:
C Programming
char *my_select_char(char *string, char c);
Implement the function body:
C Programming
char *my_select_char(char *string, char c) {
// Create a pointer to the selected character.
char *selected_char = NULL;
// Copy the string to a new buffer.
char new_string[strlen(string) + 1];
my_strcpy(new_string, string);
// Find the first occurrence of the given character in the new string.
selected_char = my_strchr(new_string, c);
// If the character is found, return a pointer to it.
// Otherwise, return NULL.
return selected_char;
}
Use the function as follows:
C
#include <stdio.h>
#include <string.h>
char *my_strcpy(char *dest, char *src);
char *my_strchr(char *string, char c);
char *my_select_char(char *string, char c);
int main() {
char string[] = "This is a test string.";
char c = 's';
// Select the given character in the string.
char *selected_char = my_select_char(string, c);
// If the character is found, print it.
if (selected_char != NULL) {
printf("The selected character is: %c\n", *selected_char);
} else {
printf("The given character was not found in the string.\n");
}
return 0;
}
Output:
The selected character is: s
Further Reading:
Implementation of strncat() in C
add source string at the end of destination string
comparing two string using strcmp and strncmp
Design a function to copy to copy string into destination string using strcpy and strncpy
how to implement implementation of strncpy in c
Design a function to calculate the length of the string using strlen
pre defined string based function
Design a function using my_strcpy and using my_strchr we need to select given char in given string
Enroll Now:
[ C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"
Contact Us:
- For any inquiries, please email us at [[email protected]].
- Follow us on insta [ electro4u_offical_ ] for updates and tips.
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!