Home > Enterprise >  What does the: = '-'; or ='/' means in strchr(I know it does locate work and str
What does the: = '-'; or ='/' means in strchr(I know it does locate work and str

Time:06-10

What does the: = '-'; or ='/' means in strchr (I know it does locate work and strrchr of last occurence)?
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; 
}

CodePudding user response:

The statements

*(strchr(str[2], ' ')) = '-'; 
*(strrchr(str[2], ' ')   1) = '/'; 

basically substitute '-' to the first space occurrence, and '/' to the last one.

  1. strchr returns the pointer to the first occurrence of the searched character (' ')
  2. * operator access that pointer
  3. the assignment substitutes the character

The string str[2], originally "and, have a nice time" will be changed into "and,-have a nice/time".

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.

CodePudding user response:

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: strchrand strcrchr 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 = '-';
  • Related