Program to remove the last comma from a string using C
Write a program in C to remove the last comma from a string. The below C program takes string having comma’s in it as input and removes the last comma from the string. The program will display the processed string on the output screen.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//Declare all the necessary variables
char *strInput="C Programming, Tutorial site";
char *strOutput;
int length = 0;
int counter = 0;
int flag = 0;
//Get the length of input string
length=strlen(strInput);
//find the position of last comma
for(counter = length-1; counter >=0; counter--){
if(strInput[counter]==','){
//position of comma is at index counter
break;
}
}
if(counter >= 0){
for(int i=0; i<length-1; i++){
if(i == counter){
//Skip the current index and copy the character at next index of input string
strOutput[i] = strInput[i + 1];
//Set flag to 1 in order to indicate we removed last comma
flag = 1;
}
else{
if(flag==1){
strOutput[i] = strInput[i+1];
}
else{
strOutput[i] = strInput[i];
}
}
}
printf("\nInput String: %s", &strInput[0]);
printf("\nOutput String: %s", &strOutput[0]);
}
else{
strOutput = strInput;
printf("\nInput String: %s", &strInput[0]);
printf("\nOutput String: %s", &strOutput[0]);
}
printf("\n\n");
return 0;
}
Here is the output of the above program:

