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

1 Answer

0 votes
#include <stdio.h>

void replace_first_char(char *s, char ch, char new_ch) {
    int i = 0;

    while (s[i] != '\0') {
        if (s[i] == ch) {
            s[i] = new_ch;
            break;
        }
        i++;
    }
}
 
int main() {
    char s[30] = "c programming";

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


 
/*
run:
 
c progranming

*/

 



answered Apr 1, 2019 by avibootz
...