C program to find last occurrence of a character in a string

Category: C Program
Tags: #cprogram#string

Learn how to write a C program to find the last occurrence of a character in a given string. This step-by-step guide explains the logic and provides a detailed code implementation, allowing you to efficiently determine the index of the last occurrence of any specified character.

Finding the last occurrence of a character in a string is a common task in programming. This article will guide you through writing a C program that accomplishes this. We’ll discuss the logic behind the program, provide the code implementation, and explain each step in detail.

Logic Behind the Program

To find the last occurrence of a character in a string:

  1. Traverse the String: Iterate through each character of the string from the beginning to the end.
  2. Track Last Occurrence: Keep updating the index whenever the target character is found.
  3. Handle No Match: If no match is found after traversing the string, indicate that the character is not present.

Write a C program to find last occurrence of a character in a string

#include <stdio.h>

int main() {
    char str[100];
    char ch;
    int position = -1; // Initialize position to -1 to indicate not found

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    printf("Enter a character to find: ");
    scanf("%c", &ch);

    // Traverse the string to find the last occurrence of the character
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ch) {
            position = i; // Update position with the index of the last occurrence
        }
    }

    // Output the result
    if (position != -1) {
        printf("The last occurrence of '%c' is at index %d.", ch, position);
    } else {
        printf("The character '%c' is not found in the string.", ch);
    }

    return 0;
}

Output

Enter a string: learn programming at procoding
Enter a character to find: o
The last occurrence of 'o' is at index 25.

Explanation of the Code

  1. Include Headers:
    • stdio.h: For input/output functions.
  2. Main Function:
    • Declare Variables:
      • str[100] to store the input string.
      • ch to store the target character.
      • position initialized to 1 to indicate the character has not been found initially.
    • Input String:
      • Takes input string from the user using fgets.
    • Input Character:
      • Takes the target character from the user using scanf.
    • Traverse the String:
      • Uses a for loop to iterate through each character of the string.
      • Compares each character with the target character ch.
      • If a match is found, updates position with the index i.
      • Continues to check until the end of the string, ensuring position holds the last occurrence index.
    • Output Result:
      • Checks the value of position. If it's not 1, prints the index of the last occurrence.
      • If position remains 1, indicates that the character is not found.

Example Walk-through

Let's illustrate this with an example:

  1. Input:
    • String: Hello, world!
    • Character: o
  2. Execution:
    • The program initializes position to 1.
    • The user inputs the string Hello, world! and the character o.
    • The program iterates through the string:
      • Index 0: H (no match)
      • Index 1: e (no match)
      • Index 2: l (no match)
      • Index 3: l (no match)
      • Index 4: o (match found, update position to 4)
      • Continue checking...
      • Index 7: o (match found, update position to 7)
    • The program completes the loop with position set to 7.
  3. Output:
    • The program prints: The last occurrence of 'o' is at index 7.

Here, we are fetching all the indexes of that character till end of string and returning that at the end. Instead what we can do is traverse string from end and when first occurrence of that character is found then break the loop.

We can use following program to traverse from last.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    char ch;
    int length, position = -1; // Initialize position to -1 to indicate not found

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    printf("Enter a character to find: ");
    scanf("%c", &ch);

    // Traverse the string to find the last occurrence of the character
    length = strlen(str);
    for (int i = length-1; i >= 0; i--) {
        if (str[i] == ch) {
            position = i; // Assign position with the index of the last occurrence
            break; // break the loop if character found
        }
    }

    // Output the result
    if (position != -1) {
        printf("The last occurrence of '%c' is at index %d.", ch, position);
    } else {
        printf("The character '%c' is not found in the string.", ch);
    }

    return 0;
}

Result will remain same but this will be more efficient.


Recommended Posts