Hey all!
Here's what I want to achieve:
1. Open up a file containing a string.
2. If the string contains the word "lists", insert the word "every" to the right of "lists" into the string.
My logic is to split the original string into 2 strings, append "every" to the first string(which contains "lists"), and then append the second string to the first(modified) string.
Is that the best solution to inserting a string into another string?
Here is the string:
This page lists toy bus by colour, engine size, transmission, weight, height, and one two, five, ten twenty.
Here's the code, which works great:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *p_openfile;
char *p_searchstring = "lists";
char *p_insertstring = " every ";
char storestring[300];
char string1[300];
char string2[300];
char *location;
int cursorposition;
int counter;
size_t tail_length;
if((p_openfile = fopen("testfile.txt", "r")) == NULL)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
fgets(storestring, 1000, p_openfile);
if((location = strstr(storestring, p_searchstring)) == NULL)
{
perror("No match was found");
exit(EXIT_FAILURE);
}
cursorposition = location - storestring;
tail_length = strlen(storestring);
memmove(string1, storestring, 14+1);
string1[15] = '\0';
strcat(string1, p_insertstring);
for(counter = cursorposition + 6; storestring[counter] != '\0'; counter++)
{ string2[counter - (cursorposition + 6)] = storestring[counter]; }
string2[counter - (cursorposition + 6)] = '\0';
strcat(string1, string2);
printf("%s", string1);
return 0;
}
EDIT: Here's the output:
Code:
This page lists every toy bus by colour, engine size, transmission, weight, height, and one two, five, ten twenty.
Also, I used memmove(), but I could also have used strncpy(). Is there any real difference between them?
Thanks in advance?