How to replace the last occurrence of a character in a string using C

1 Answer

0 votes
#include <stdio.h>

void replace_last_char(char *s, char ch, char new_ch) {
    int i = 0, lastIndex = -1;

    while (s[i] != '\0') {
        if (s[i] == ch) {
            lastIndex = i;
        }
        i++;
    }

    if (lastIndex != -1) {
        s[lastIndex] = new_ch;
    }
}
 
int main() {
    char s[30] = "c programming";

    replace_last_char(s, 'm', 'n');
    
    puts(s);
}


 
/*
run:
 
c programning

*/

 



answered Apr 2, 2019 by avibootz

Related questions

...