OneBite.Dev - Coding blog in a bite size

find the last occurrence of a character in a string in C

Code snippet on how to find the last occurrence of a character in a string in C

  #include <string.h>

// Function to find the last occurrence of a character in a string
char* FindLastOccurrence(const char* str, char ch)
{
	int len = strlen(str);
	char* result = NULL;

	for (int i = 0; i < len; i++)
	{
		if (str[i] == ch)
			result = (char*)&str[i];	
	}

	return result;
}

The code begins by including the string library, which contains functions for manipulating strings. Then, a function is declared called FindLastOccurrence which will take two arguments; a const char array and a character. Then, the length of the string is stored in a variable called len. Next, a pointer of type character is declared and initialized to NULL which will be used to store the last occurrence of the given character. Finally, a for loop is used to iterate through each character in the string. If the character at the current index is equal to the character given as an argument, the pointer to it is stored in the result variable. The last occurrence of the character is then returned.

c