How to implement the strrchr function in C

1 Answer

0 votes
#include <stdio.h>

char* strrchr(const char* s, int c) {
	// find last occurrence of c in s
	const char ch = c;
	const char* p;

	for (p = NULL; ; s++) {
		if (*s == ch)
			p = s;
		if (*s == '\0')
			return (char*)p;
	}
}



int main(void)
{
	const char str[] = "https://www.seek4info.com";
	const char ch = '.';

	char* result = strrchr(str, ch);

	printf("index = %d\n", result - str);
	printf("%s\n", result);
	printf("%c", str[21]);

	return 0;
}




/*
run:

index = 21
.com
.
 
*/

 



answered Dec 19, 2022 by avibootz

Related questions

...