Reputation: 25
Search for a string variable within another string variable while avoiding the usage of any function in the <string.h> library. Im not sure why my code isnt working. Any suggestions or alternative methods are very appreciated. edit: it's ok to use strlen but not other functions
#include <stdlib.h>
#include<string.h>
#include <stdio.h>
int strsearch(char *B, char *C);
int main()
{
char B[]= "thisatest";
char C[]= "tes";
strsearch(B, C);
return 0;
}
int strsearch(char *B, char *C ){
int i, b, c, k;
k= -1;
b= strlen(B);
c= strlen(C);
for (i=0; i<b; i++){
if (B[i+c]== C)
return i;
return -1;
}
}
Upvotes: 1
Views: 71
Reputation: 117962
Your return -1;
is within the loop. It'll return if the first if (B[i+c]== C)
comparison you do fails. Move it out of the loop.
You compare the wrong things. B[i+c]
is a char
and C
is a char*
. If you want to compare strings, use strcmp
, strncmp
or memcmp
depending on the situation and supply the correct arguments.
strcmp
for arbitrary strings that you want to compare until the null terminator is found in both.strncmp
if you want to limit the comparison to n
number of characters but still be stopping at a null terminator. Seems like a good fit for a substring comparison.memcmp
if you are sure that the length you supply will not make it pass a null terminator since it doesn't check for a null terminator. It just compare bytes in memory where you tell it to, for as long as you tell it to.I'm using memcmp
in this example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SS_NOTFOUND ((size_t)-1)
size_t strsearch(const char *B, const char *C) {
size_t Blen = strlen(B);
size_t Clen = strlen(C);
// If Blen < Clen, there's no way C can
// can be a substring of B:
if(Blen < Clen) return SS_NOTFOUND;
// Subtract the length of C from the length of B. There is no need to
// search in B beyond the point where C can't fit:
Blen -= Clen;
for (size_t i = 0; i <= Blen; i++) {
// memcmp is fine here since no null terminators will be passed
// due to the check (Blen < Clen) at the start and the subtraction
// of Clen from Blen above.
if (memcmp(B + i, C, Clen) == 0) return i;
// char* char*
}
return SS_NOTFOUND;
}
int main() {
char B[] = "thisatest";
char C[] = "tes";
size_t pos = strsearch(B, C);
if(pos == SS_NOTFOUND) puts("sorry, not found");
else printf("Found at index %zu\n", pos);
}
Output:
Found at index 5
If you for some reason can't use memcmp
, create your own and use that instead in the example above:
int MemCmp(const void *s1, const void *s2, size_t len) {
const unsigned char* a = s1;
const unsigned char* b = s2;
for(;len; --len, ++a, ++b) {
if(*a < *b) return -1;
else if(*a > *b) return 1;
}
return 0;
}
Upvotes: 1