Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

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

๐ŸŒ™