I wrote this function which does the following from scratch w/o looking for ways that it is typically done:
- Accepts a
char c
to search for. - Accepts a
char* str
to search within. - Accepts a buffer pointer, and stores all indices of
c
that are instr
inside the provided buffer. - Returns the # of times that
c
was found instr
.
Please critique and also - Are there better alternatives to export the indices other than using a buffer ptr?
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int str_contains(const char c, const char* str, int* output_buffer){
int i, str_len;
str_len = strlen(str);
int *holder = malloc(str_len*sizeof(int));
int holder_iteration = 0;
for(i = 0; i < str_len; i++){
if(str[i] == c){
holder[holder_iteration++] = i;
}
}
memcpy(output_buffer,holder,holder_iteration*sizeof(int));
free(holder);
return holder_iteration;
}
int main(){
char* myString = "Welcome to the jungle, baby. Do you like to juggle or jump around?";
int* output = malloc(500*sizeof(int));
int number = str_contains('a',myString,output);
printf("# of times: %d\nIndices: \n",number);
int i;
for(i = 0; i < number; i++){
printf("%d\n",output[i]);
}
free(output);
return(EXIT_SUCCESS);
}