Advertisement
Nabil-Ahmed

Untitled

Jul 26th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. //Wap to insert a char into a string//
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. void insert_substring(char*, char*, int);
  7. char* substring(char*, int, int);
  8.  
  9. int main()
  10. {
  11.    char text[100], substring[100];
  12.    int position;
  13.  
  14.    printf("Given word\n");
  15.    gets(text);
  16.  
  17.    printf("Character to insert\n");
  18.    gets(substring);
  19.  
  20.    printf("At which position\n");
  21.    scanf("%d", &position);
  22.  
  23.    insert_substring(text, substring, position);
  24.  
  25.    printf("%s\n",text);
  26.  
  27.    return 0;
  28. }
  29.  
  30. void insert_substring(char *a, char *b, int position)
  31. {
  32.    char *f, *e;
  33.    int length;
  34.  
  35.    length = strlen(a);
  36.  
  37.    f = substring(a, 1, position - 1 );
  38.    e = substring(a, position, length-position+1);
  39.  
  40.    strcpy(a, "");
  41.    strcat(a, f);
  42.    free(f);
  43.    strcat(a, b);
  44.    strcat(a, e);
  45.    free(e);
  46. }
  47.  
  48. char *substring(char *string, int position, int length)
  49. {
  50.    char *pointer;
  51.    int c;
  52.  
  53.    pointer = malloc(length+1);
  54.  
  55.    if( pointer == NULL )
  56.        exit(EXIT_FAILURE);
  57.  
  58.    for( c = 0 ; c < length ; c++ )
  59.       *(pointer+c) = *((string+position-1)+c);
  60.  
  61.    *(pointer+c) = '\0';
  62.  
  63.    return pointer;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement