C Programming Code Examples C > Strings Code Examples program to replace first occurrence of a character in a string program to replace first occurrence of a character in a string Write a C program to replace first occurrence of a character with another character in a string. How to replace first occurrence of a character with another character in a string using loop in C programming. Logic to replace first occurrence of a character in given string. Logic to replace first occurrence of a character Input string from user, store it in some variable say str. Input character to replace and character new character from user, store it in some variable say oldChar and newChar. Run a loop from start of string str to end. The loop structure should loop like while(str[j]!='\0') Inside the loop check if(str[j] == oldChar). Then, swap old character with new character i.e. str[j] = newChar and terminate the loop. /* C program to replace first occurrence of a character with another in a string */ #include <stdio.h> #define maxsize 100 // Maximum string size /* Function declaration */ void replaceFirst(char * str, char oldChar, char newChar); int main() { char str[maxsize], oldChar, newChar; printf("Enter any string: "); gets(str); printf("Enter character to replace: "); oldChar = getchar(); // Used to skip extra ENTER character getchar(); printf("Enter character to replace '%c' with: ", oldChar); newChar = getchar(); printf("\nString before replacing: %s\n", str); replaceFirst(str, oldChar, newChar); printf("String after replacing first '%c' with '%c' : %s", oldChar, newChar, str); return 0; } /* Replace first occurrence of a character with another in given string. */ void replaceFirst(char * str, char oldChar, char newChar) { int j=0; /* Run till end of string */ while(str[j] != '\0') { /* If an occurrence of character is found */ if(str[j] == oldChar) { str[j] = newChar; break; } j++; } }