Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

C program to replace a substring in a string with a new string using strstr and string functions

Replace Substring in a String - C Program

πŸ“ Replace Substring in a String (C Program)

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

int main()
{
    char mainstr[200], substr[100], newstr[100], result[300];
    char *pos;
    int index = 0;

    printf("Enter the main string:\n");
    scanf(" %[^\n]", mainstr);

    printf("Enter the substring to remove:\n");
    scanf(" %[^\n]", substr);

    printf("Enter the new string to insert:\n");
    scanf(" %[^\n]", newstr);

    pos = strstr(mainstr, substr);

    if (pos == NULL)
    {
        printf("Modified string: %s\n", mainstr);
    }
    else
    {
        index = pos - mainstr;
        strncpy(result, mainstr, index);
        result[index] = '\0';

        strcat(result, newstr);
        strcat(result, pos + strlen(substr));

        printf("Modified string: %s\n", result);
    }

    return 0;
}
  

πŸ“˜ Explanation:

  • Reads a main string, a substring to remove, and a new string to insert.
  • Uses strstr() to find the first occurrence of the substring.
  • Replaces the substring by reconstructing the final string using strncpy, strcat, and pointer arithmetic.
  • If the substring is not found, it simply prints the original string.

πŸ§ͺ Sample Output:

Enter the main string:
I love programming in C
Enter the substring to remove:
programming
Enter the new string to insert:
coding
Modified string: I love coding in C
    

🏷️ Keywords:

replace substring in C, strstr example, string manipulation, string replace, C string replace, beginner C program

Comments

Popular Posts

πŸŒ™