Home > Software design >  Replace 3 first elements of string by other 2 from keyboard in C
Replace 3 first elements of string by other 2 from keyboard in C

Time:01-21

I don't know how to Replace 3 first elements of string by other 2 from keyboard in C. Can I change the 2th and 3th and print from the 2th?

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main()
{
    char c[] = "my string";
    int i=0;

    for (i=0; i<strlen(c); i  ){
        if(i==0 || i==1 || i==2){
            printf("Enter a character to replace %dth element: ", i 1);
            scanf(" %c", &c[i]);
        }
    }
    printf("\nString is: %s", c);
}

In the following code, we have treated string as an array and in the for loop there is a if statement which checks for the first 3 characters of the string
then we just replace the letters using scanf, in scanf(" %c", &c[i]);, NOTE that there is a space before %c, it is because if that is not done the 2nd scanf will get skipped because of the new line from 1st scanf()

Hpe that solves your problem. Thank You!

CodePudding user response:

that would not be doing what you are asked to do (modify the strings first 3 chars).

Not going to provide actual code, have a go from these hints. If you get stuck post actual code

  • create new string thats one shorter that length of old string 1
  • put new 2 chars in new string at pos 0 and 1
  • copy 4th char onwards (offset 3) into new string at 3rd position (offset 2)
  •  Tags:  
  • Related