This blog is under construction

Thursday 18 July 2013

C program to insert a word in a string

Write a C program to insert a word into the string at the given location.


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

  int main() {
        char string[256], word[256], output[512];
        int i, j, k, location;

        i = j = k = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(string, 256, stdin);
        string[strlen(string) - 1] = '\0';

        /* get the input word from the user  */
        printf("Enter the word to insert:");
        fgets(word, 32, stdin);
        word[strlen(word) - 1] = '\0';

        /* get the desired location to insert input word */
        printf("Enter your desired location(0-%d):", strlen(string) - 1);
        scanf("%d", &location);

        /* copying characters present before the given location */
        for (i = 0; i < location; i++) {
                output[j++] = string[i];
        }

        /* copying the given word */
        while (word[k] != '\0') {
                output[j++] = word[k++];
        }

        /* copying characters present after the given location */
        while (string[i] != '\0') {
                output[j++] = string[i++];
        }

        output[j] = '\0';

        /* print the result */
        printf("Resultant String: %s\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out 
  Enter your input string:helloworld
  Enter the word to insert:       //given space as i/p
  Enter your desired location(0-9):5 
  Resultant String: hello world


No comments:

Post a Comment