Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

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

๐ŸŒ™