Skip to main content

Featured

C Pattern Programs: Square Number and Alphabet Patterns Explained

πŸ”· Square Star Pattern πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("* ");//keep"* " } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Column-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = num; i >= 1; i--) { for(int j = num; j >= 1; j--) { printf("%c ", j + 64);//%c for Character and 64 will be ASIIC VALUE } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Row-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; ...

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

πŸŒ™