MaMu
MaMu

Reputation: 1869

Finding last occurence of string

I want to find the last occurrence of string in a string (which is not NULL- terminated). The searched substring is always 4 letters long. This is what I tried:

char * strrstr(char *string, char *find, ssize_t len)
{
  //I see the find in string when i print it 
  printf("%s", string);
  char *cp;
  for (cp = string + len - 4; cp >= string; cp--)
  {
    if (strncmp(cp, find, 4) == 0)
        return cp;
  }
  return NULL;
}

It gives me NULL all the time although I see the substring, which I'm looking for in string argument.

Upvotes: 4

Views: 5631

Answers (1)

MOHAMED
MOHAMED

Reputation: 43518

I tried your code in this way and it works successfully

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * strrstr(char *string, char *find, ssize_t len)
{
  //I see the find in string when i print it 
  //printf("%s", string);
  char *cp;
  for (cp = string + len - 4; cp >= string; cp--)
  {
    if (strncmp(cp, find, 4) == 0)
        return cp;
  }
  return NULL;
}

int main() {
   char *ret = strrstr("kallelkallelkallelkallaa", "kall", 23);
   printf("%s", ret); //---> it prints: kallaa
   return 0;
}

Upvotes: 3

Related Questions