Write a function that locates a character in a string.Prototype: char *_strchr(char *s, char c);Returns a pointer to the first occurrence of the character c in the string s, or NULL if the character is not found
Question
Write a function that locates a character in a string.Prototype: char *_strchr(char *s, char c);Returns a pointer to the first occurrence of the character c in the string s, or NULL if the character is not found
Solution
Sure, here is a simple implementation of the function in C:
#include <stdio.h>
char *_strchr(char *s, char c) {
while (*s != '\0') {
if (*s == c)
return s; // return the pointer if character found
s++;
}
if (*s == c)
return s;
return NULL; // return NULL if character not found
}
int main() {
char str[] = "Hello, World!";
char c = 'o';
char *result = _strchr(str, c);
if (result != NULL)
printf("First occurrence of '%c' in '%s' is at position: %ld\n", c, str, result-str);
else
printf("Character '%c' not found in '%s'\n", c, str);
return 0;
}
This function _strchr takes a string s and a character c as input. It iterates over the string until it finds the character c or reaches the end of the string. If the character is found, it returns a pointer to the first occurrence of the character, otherwise it returns NULL. The main function demonstrates how to use this function.
Similar Questions
char *_strchr(char *s, char c)
Which of the following function is used to find the first occurrence of a given string in another string? ans. strchr() strnset() strrchr() strstr()
#ifndef main.h#define main.h#include <stddef.h>int _putchar(char c);int _islower(int c);int _isalpha(int c);int _abs(int n);int _isupper(int c);int _isdigit(int c);int _strlen(char *s);void _puts(char *s);char *_strcpy(char *dest, char *src);int _atoi(char *s);char *_strcat(char *dest, char *src);char *_strncat(char *dest, char *src, int n);char *_strncpy(char *dest, char *src, int n);int _strcmp(char *s1, char *s2);char *_memset(char *s, char b, unsigned int n);char *_memcpy(char *dest, char *src, unsigned int n);char *_strchr(char *s, char c);unsigned int _strspn(char *s, char *accept);char *_strpbrk(char *s, char *accept);char *_strstr(char *haystack, char *needle);#endif main.h~ ~ ~
What is the first argument of the strcat() function in C programming?
#include <stdio.h> #include <string.h> int main() { char *str = "hello, world"; char str1[9]; strncpy(str1, str, 9); printf("%s %d", str1, strlen(str1)); }
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.