How to find the the last occurrence of a substring in a string with C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>

static char *strrstr(const char *haystack, const char *needle) {
    if (needle == NULL) 
        return (char *) haystack;

    char *rv = NULL;
    while (1) {
        char *p = strstr(haystack, needle);
        if (p == NULL)
            break;
        rv = p;
        haystack = p + strlen(needle);
    }

    return rv;
}

	
int main()
{
	char url[] = "http://www.abcwebsite.com/abc/xyz";
	
	char *p = strrstr(url, "abc");

    puts(p);

    return 0;
}
  
  
/*
run:
  
abc/xyz
  
*/

 



answered Feb 19, 2020 by avibootz
edited Feb 20, 2020 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

static char *strrstr(const char *haystack, const char *needle) {
    if (needle == NULL) 
        return (char *) haystack;

    char *rv = NULL;
    while (1) {
        char *p = strstr(haystack, needle);
        if (p == NULL)
            break;
        rv = p;
        haystack = p + strlen(needle);
    }

    return rv;
}

	
int main()
{
	char url[] = "http://www.abcwebsite.com/abc/xyz";
	char subs[] = "abc";
	
	char *p = strrstr(url, subs);

    puts(p);

    return 0;
}
  
  
/*
run:
  
abc/xyz
  
*/

 



answered Feb 19, 2020 by avibootz
edited Feb 20, 2020 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
 
static char *strrstr(const char *haystack, const char *needle) {
    if (needle == NULL) 
        return (char *) haystack;
 
    char *rv = NULL;
    while (1) {
        char *p = strstr(haystack, needle);
        if (p == NULL)
            break;
        rv = p;
        haystack = p + strlen(needle);
    }
 
    return rv;
}
 
     
int main()
{
    char url[] = "http://www.abcwebsite.com/abc/xyz";
     
    char *p = strrstr(url, NULL);
 
    puts(p);
 
    return 0;
}
   
   
/*
run:
   
http://www.abcwebsite.com/abc/xyz
  
*/
   

 



answered Feb 20, 2020 by avibootz
...