Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a FORTRAN program that, given three string strings, the program will repla

ID: 3571506 • Letter: W

Question

Write a FORTRAN program that, given three string strings, the program will replace all occurrences of the 2nd string with the 3rd string in the first string and display the modified string.

Example 1 Input:

This is the input string.

is

was

Will produce the output:

This was the input string.

Example 2 Input:

Now is the time for all good men to come to the aid of somebody.

o

0

Will produce the output:

N0w is the time f0r all g00d men t0 c0me t0 the aid 0f s0meb0dy.

Assume that the input strings may be no longer than 79 characters and are input, in order, one line at a time.

Explanation / Answer

Try this,

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

/** Define the max character length */

#define MAX_L 4096

/** Proto types */

void replace (char *, char *, char *);

int main(void) {

    char o_string[MAX_L], s_string[MAX_L], r_string[MAX_L];

    printf("Please enter the original string ..(max length %d characters): ", MAX_L);

    fflush(stdin);

    gets(o_string);

    printf(" Please enter the string to search string (max length %d characters): ", MAX_L);

    fflush(stdin);

    gets(s_string);

    printf(" Please enter the replace string (max length %d characters): ", MAX_L);

    fflush(stdin);

    gets(r_string);

    printf(" The Original string is ************************************* ");

    puts(o_string);

    replace(o_string, s_string, r_string);

    printf(" The replaced string ************************************* ");

    puts(o_string);

    return 0;

}

void replace(char * o_string, char * s_string, char * r_string) {

      //a buffer variable to do all replace things

      char buffer[MAX_L];

      //to store the pointer returned from strstr

      char * ch;

      // This is first exit condition

      if(!(ch = strstr(o_string, s_string)))

              return;

      //copy all the content to the buffer before the first occurrence of the search string

      strncpy(buffer, o_string, ch-o_string);

      //prepare the buffer for appending by adding null to the end of it

      buffer[ch-o_string] = 0;

      //append using sprintf function

      sprintf(buffer+(ch - o_string), "%s%s", r_string, ch + strlen(s_string));

      //empty o_string for copying the string

      o_string[0] = 0;

      strcpy(o_string, buffer);

      //pass recursively to replace other occurrences

      return replace(o_string, s_string, r_string);

}

Thank You.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote