|
|
Subject:
Help with strchr() and strrchr()...
Category: Computers > Programming Asked by: zefyre-ga List Price: $5.00 |
Posted:
10 Feb 2004 06:28 PST
Expires: 11 Mar 2004 06:28 PST Question ID: 305348 |
Hi, In a previous question, hammer-ga wrote the following function for me... char *es_strrclip_pointer(char needle, char *haystack) { char *endpos; char *retval; retval = NULL; if(haystack != NULL) { retval = (char *)strdup(haystack); if(retval != NULL) { endpos = strrchr(retval, needle); if(endpos != NULL) { endpos++; *endpos = '\0'; } else { retval = NULL; fprintf(stderr, "Needle not found in Haystack.\n"); } } else { fprintf(stderr, "Strdup failed.\n"); } } else { fprintf(stderr, "Haystack is NULL.\n"); } return(retval); } I was wondering if I could get a commented version of this, so I can get a better grip on how it works. Thanks! -- Quinn |
|
Subject:
Re: Help with strchr() and strrchr()...
Answered By: majortom-ga on 10 Feb 2004 06:56 PST Rated: |
Here you are: * * * Cut Here * * * char *es_strrclip_pointer(char needle, char *haystack) { char *endpos; char *retval; /* Initialize return value to null */ retval = NULL; /* Make sure haystack is not null */ if(haystack != NULL) { /* Allocate a copy of the haystack string; strdup ** is equivalent to: ** char *copy = malloc(strlen(s) + 1); ** strcpy(copy, s); */ retval = (char *)strdup(haystack); /* Make sure memory allocation did not fail if(retval != NULL) { /* strrchr returns a pointer to the LAST occurrence ** of 'needle' in 'retval' (our copy of haystack) */ endpos = strrchr(retval, needle); /* If the needle was found... */ if(endpos != NULL) { /* Move one character PAST needle... */ endpos++; /* And make that character a null, ending ** the string at that point. retval is now a ** copy of haystack up to and including ** needle */ *endpos = '\0'; } else { /* No needle in the haystack */ retval = NULL; fprintf(stderr, "Needle not found in Haystack.\n"); } } else { /* Memory allocation failure */ fprintf(stderr, "Strdup failed.\n"); } } else { /* Haystack was a null pointer, not a valid string */ fprintf(stderr, "Haystack is NULL.\n"); } /* Return our copy of haystack up to and including needle. ** Returned string should eventually be freed with free() by caller */ return(retval); } |
zefyre-ga
rated this answer:
and gave an additional tip of:
$2.50
Thanks for the quick response! The comments to the code were very easy to understand, and cleared up everything I had been wondering about. Great job! |
|
There are no comments at this time. |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
Search Google Answers for |
Google Home - Answers FAQ - Terms of Service - Privacy Policy |