Test this out. If it works OK, then the functions in the program, are working OK, and the problem is that the "1" and the "one" were not being treated as strings with an end of string char - which is a common cause of unwanted char's on the end of a string.
If it fails, then we know that one or more of the functions is causing the error.
I've tested your program (as I posted in #21 reply above), and in Pelles C, it works correctly. The original program did not, but the version above, works correctly, in limited testing.
It's not easy to debug a program that keeps working correctly in your compiler!
Code:
#include <stdio.h>
#include <stdbool.h>
void replaceString (char source[],char s1[], char s2[]);
int findString (const char source[], const char s[]);
int main (void) {
int i;
char source[]={"one time let this work"};
char s1[]= {"1"};
char s2[]= {"one"};
/*here, s1 and s2 are definitely string arrays, and not merely chars */
replaceString(source, s1, s2);
printf("\n"); //added
return 0; //these two lines
}
void replaceString (char source[],char s1[], char s2[])
{
void removeString (char source[], int i, int remove);
void insertString (char source[], char insert[], int p);
int i = findString(source, s2);
//printf("i: %d\n",i);getchar(); //just for bug check
int count=0; //the variable that needed initialization
while (s2[count] != '\0')
count++;
removeString(source, i, count);
insertString(source, s1, i);
printf("%s\n", source);
}
int findString (const char source[], const char s[])
{
int i, j, foundit = false;
for ( i = 0; source[i] != '\0' && !foundit; ++i ) {
foundit = true;
for ( j = 0; s[j] != '\0' && foundit; ++j )
if ( source[j + i] != s[j] || source[j + i] == '\0' )
foundit = false;
if (foundit)
return i;
}
return -1;
}
void removeString (char source[], int i, int remove)
// "i" is where to start removing (from findString) and "remove" is # of characters
// to remove
{
char result[81];
int j;
int k = 0;
for (j = 0; j < i; j++)
result[j] = source[j];
while (source[j + remove] != '\0')
{
result[j] = source[j + remove];
j++;
}
while (result[k] != '\0')
{
source[k] = result[k];
k++;
}
source[k] = '\0';
}
void insertString (char source[], char insert[], int p)
// p is where to start inserting and insert[] is what to insert
{
int i = 0;
int j = 0;
char temp[81];
// convert source to a temp
while (source[i] != '\0')
{
temp[i] = source[i];
i++;
}
temp[i + 1] = source[i + 1];
//change source to insert p
while (insert[j] != '\0')
{
source[j + p] = insert[j];
j++;
}
// add back characters deleted by insertion by taking from temp and place after insert
while (temp[p] != '\0')
{
source[j + p] = temp[p];
p++;
}
source[j + p] = '\0';
}
Try that, with several different s1 and s2 strings.