Reputation: 13
What does the = '-';
or = '/'
mean in strchr
(I know it does locate work and strrchr
of last occurrence)?
This code does create two files.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fpA = fopen("output_A.txt", "w");
FILE *fpB = fopen("output_B.txt", "w");
char *strA = ",-/";
char temp[100];
char str[5][60] = { { "summer is coming!" },
{ "vacation will let you chill out" },
{ "and, have a nice time" },
{ "and, stay fit" },
{ "and, wish you the best" }, };
fprintf(fpA, "%s\n", str[0]);
fprintf(fpB, "%s\n", str[1]);
fclose(fpA);
fclose(fpB);
fpA = fopen("output_A.txt", "r");
fpB = fopen("output_B.txt", "w");
*(strchr(str[2], ' ')) = '-';
*(strrchr(str[2], ' ') + 1) = '/';
strtok(str[2], strA);
strcpy(temp, strtok(NULL, strA));
str[1][8] = '\n';
str[1][9] = '\0';
strncat(temp, str[1], strlen(str[1]));
if (strcmp(str[3], str[4]))
strcat(temp, str[3]);
else
strcat(temp, str[4]);
fprintf(fpA, "%s", temp);
fprintf(fpB, "%s", temp);
fclose(fpA);
fclose(fpB);
return 0;
}
Upvotes: 0
Views: 105
Reputation: 495
It searches for ' '
, then it assigns '-'
to the position it found the first/last occurrence of ' '
(depending on strchr
, strrchr
). I don't really know why would it do that, but that's what the code is doing.
Sidenote: strchr
and strrchr
return NULL
when no match for delimiter
is found in the string. If the string were to have no spaces, your code would be segfaulting.
An improvement could be:
char* aux = strchr(str[2], ' ');
if (aux != NULL)
*aux = '-';
Upvotes: 1
Reputation: 7490
The statements
*(strchr(str[2], ' ')) = '-';
*(strrchr(str[2], ' ') + 1) = '/';
basically substitute '-'
to the first space occurrence, and '/'
to the character next to the last space occurrence.
The first substitution:
strchr
returns the pointer to the first occurrence of the searched character (' '
)*
operator access that pointer'-'
The second substitution:
strrchr
returns the pointer to the last occurrence of the searched character (' '
)*
operator access the pointer'/'
The string str[2]
, originally "and, have a nice time"
will be changed into "and,-have a nice /ime"
.
Warning: you need to check strchr
and strrchr
return values, as they can return NULL
if the searched character is not found (check this out).
If that's the case, dereferencing the pointer will lead to Undefined Behavior (probably a segmentation fault on modern computers), making your program crash.
Upvotes: 5