#include "stdio.h"
#include "string.h"
/* for strcpy and strcat */
#define MAXLINE 100
extern int getline(char [], int);
int main()
{
char string1[MAXLINE], string2[MAXLINE];
int len1, len2;
char newstring[MAXLINE*2];
printf("enter first string:\n");
len1 = getline(string1, 100);
printf("enter second string:\n");
len2 = getline(string2, 100);
if(len1 == EOF || len2 == EOF)
exit(1);
strcpy(newstring, string1);
strcat(newstring, string2);
printf("%s\n", newstring);
return 0;
}
Exercise 5. Write a function to find a substring in a larger string and replace it with a different substring.
Here is one way. (Since the function doesn't return anything, I've defined it with a return type of void.)
void replace(char string[], char from[], char to[])This code is very similar to the mystrstr function in the notes, chapter 10, section 10.4, p. 8. (Since strstr's job is to find one string within another, it's a natural for the first half of replace.)
{
int start, i1, i2;
for(start = 0; string[start] != '\0'; start++)
{
i1 = 0;
i2 = start;
while(from[i1] != '\0')
{
if(from[i1] != string[i2])
break;
i1++;
i2++;
}
if(from[i1] == '\0')
{
for(i1 = 0; to[i1] != '\0'; i1++)
string[start++] = to[i1];
return;
}
}
}
Extra credit: Think about what replace() should do if the from string appears multiple times in the input string.
Our first implementation replaced only the first occurrence (if any) of the from string. It happens, though, that it's trivial to rewrite our first version to make it replace all occurrences--just omit the return after the first string has been replaced:
void replace(char string[], char from[], char to[])
{
int start, i1, i2;
for(start = 0; string[start] != '\0'; start++)
{
i1 = 0;
i2 = start;
while(from[i1] != '\0')
{
if(from[i1] != string[i2])
break;
i1++;
i2++;
}
if(from[i1] == '\0')
{
for(i1 = 0; to[i1] != '\0'; i1++)
string[start++] = to[i1];
}
}
}
No comments:
Post a Comment