Y
Y
Yurii Vlasiuk2016-03-13 23:46:46
Programming
Yurii Vlasiuk, 2016-03-13 23:46:46

Replacing one character in a string with another, how to do it in C?

I need to write a program Replacing one character in a string with another in C
So I did, but it doesn’t work, I really ask for help

#include <stdio.h>
#include <string.h>
int main ()
{
  char String[20];
  char new[1];
  char target[1];
  char editString[20];
  int i=0;

  printf("Enter string to edit  ");
  scanf("%s", String);

  printf("Enter targer symbol  ");
  scanf( "%s", target);

  printf("Enter new symbol  ");
  scanf( "%s", new);

  for(i=0; i<strlen(String); i++) 
  {
    if(String[i] == target[0]) 
    {

      editString[i] = new[0];
    }
    else
    {
      editString[i]=String[i];
    }
  }
  printf( "Editing string: %s", editString );
  printf( "\n");
  
  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2016-03-13
@forestyura

The main problem is that your arrays are substitution strings of 1 char in size. And at least 2 will be written: the entered character and the end-of-line character.

R
res2001, 2016-03-14
@res2001

It would be nice to add '\0' to the editString at the end. In this form, as it works now, while the arrays are on the stack, it is worthwhile to start allocating them dynamically and this will pop up for you.
And replace "new" with another name, because new is a function word in C++, and from C to C++ one step actually :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question