Answer to Question #182322 in C for kate

Question #182322

Write a program that accepts string from the user and allow the user to delete a  specified character from a string inputted.


1
Expert's answer
2021-04-19T14:35:07-0400
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 256

int main() {
  char buffer[BUFFER_SIZE];
  printf("Enter string: ");
  if (!fgets(buffer, BUFFER_SIZE, stdin)) {
    printf("[Error] Can't read from stdout\n");
    exit(1);
  }
  printf("Enter a character you wish to delete: ");
  char c;
  scanf("%c", &c);

  size_t i = 0;
  size_t len = strlen(buffer);
  while (i < len && buffer[i] != c) i++;
  if (i != len) {
    for (size_t j = i; j < len; j++) {
      if (buffer[j] != c) {
        buffer[i] = buffer[j];
        i++; 
      }
    }
  }
  buffer[i] = '\0';
  printf("%s", buffer);
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS