LOOK!
Code:
#include<stdio.h>
#include<string.h>
#define MAX 25
int main(void)
{
int ch;
char *str[] = {
"You Know",
"That i learning programming",
"Because im interested",
"And its cool",
"When i get confused for debugging",
"After i succeed, i feel relieved",
"So i will learning and using it",
"Even i have no life"
};
int i;
char str1[MAX];
char str2[MAX];
char *strloc;
printf("%s",str[3]);
printf("\nNow Choose Available String in [3]:\n");
fgets(str1,MAX,stdin);
printf("Then Insert The New String:\n");
fgets(str2,MAX,stdin);
char *p1,*p2;
if ((p1 = strchr(str1,'\n')) != NULL) *p1 = '\0';
if ((p2 = strchr(str2,'\n')) != NULL) *p2 = '\0';
strloc = strstr(str[3],str1);
strncpy(strloc,str2,strlen(str2));
while((ch = getchar()) != '\n' && ch != EOF);
getchar();
return 0;
}
this is from exercise Let Us C book i get from online
the objective located the available string in line and replacing with other string
Example:
char str[5] = "After i succeed, i feel relieved";
if "succeed" string is replacing with new string like "failed"
the new line has to be
char str[5] = "After i failed, i feel relieved";
im surfing the internet c string reference and i got the wonderful function in string.h that is
strstr() function
which located the same string and with
strncpy() function
the string will changed
but seems strstr() function must using string constant (i use *strloc) in this case.
that's the problem
i get confused with line
strloc = strstr(str[3],str1)
str[3] was a string constant based on array, the declaration are *str[] which related to multidimensional array.
i think that cause this program to be error.
because when i using the reference from internet, the program was executed for sure.
This code what i mean
Code:
#include <stdio.h>
#include <string.h>
#define MAX 10
int main ()
{
int ch;
char str[] ="This is a simple string";
char str1[MAX];
char str2[MAX];
printf("Insert The Same String:\n");
fgets(str1,MAX,stdin);
printf("Insert The Replacing String:\n");
fgets(str2,MAX,stdin);
char *p1,*p2;
if ((p1 = strchr(str1,'\n')) != NULL) *p1 = '\0';
if ((p2 = strchr(str2,'\n')) != NULL) *p2 = '\0';
char *pch;
pch = strstr(str,str1);
strncpy (pch,str2,strlen(str2));
puts(str);
while((ch = getchar()) != '\n' && ch != EOF);
getchar();
return 0;
}
and rather than that i didnt have anymore idea to make that replacing string.
anyhelp will appreciated
Thank You!
PS: This is only exercise for me, not a homework, so lets discuss this matter if u want to