๐Ÿ’ป
B.TECH I YEAR โ€ข I SEMESTER โ€ข R25

Programming for Problem Solving - Lab Manual

C Programming Laboratory โ€ข Program Solution

๐Ÿ“˜ R25 Regulation ๐ŸŽ“ I Year ๐Ÿ“š I Semester ๐Ÿ’ป C Programming ๐Ÿงช Lab Program
Selected Program

Write a C program that uses functions to insert a sub-string into a given main string from a given position.

โ† All Lab Programs

Write a C program that uses functions to insert a sub-string into a given main string from a given position.

C Program
//insert a sub-string into a given main string from a given position.
#include <stdio.h>
#include <string.h>

int main() {
    char mainStr[50], subStr[50],finalStr[100];
    int position;

    // Input the main string
    printf("Enter the main string: ");
     fgets(mainStr, sizeof(mainStr), stdin);  
    
    // Input the substring
    printf("Enter the substring: ");
    fgets(subStr, sizeof(subStr), stdin); 
    subStr[strcspn(subStr, "\n")] = '\0';  // Remove newline  

    // Input the position
    printf("Enter the position to insert the substring: ");
    scanf("%d", &position);

    // Check if the position is valid
    int mainLen = strlen(mainStr);
    if (position < 0 || position > mainLen) {
        printf("Invalid position.\n");
        return 1;
    }
    
    strncpy(finalStr,mainStr,position);  // Copy string up to position
    strcat(finalStr,subStr);    // Insert substring
    strcat(finalStr,mainStr+position);  // Append remaining part
  
    // Print the result string
    printf("Modified string: %s\n", finalStr);

    return 0;
}

OUTPUT
Enter the main string: welcome to Glance
Enter the substring: Study
Enter the position to insert the substring: 11
Modified string: welcome to StudyGlance 

๐Ÿ’ป Run This C Program

Write a C program that uses functions to insert a sub-string into a given main string from a given position.
The selected C program is loaded automatically. Edit the code, provide input through STDIN and click Run.

The compiler is embedded using OneCompiler. Your program runs in the embedded C environment; Study Glance does not execute C code directly on your web server.
โ† Back to PPS Lab Programs ๐Ÿ“š All Lab Manuals