Reputation: 19
I have two char
arrays char search_array[8]
and input_array[30]
and I'm getting the characters by using getchar
, but I want to find if the search array exists in input array without using string library.
Example:
search array: hello
input array hello, how are you
Upvotes: 0
Views: 315
Reputation: 144740
The obvious solution for your goal is to use the standard library's strstr
function.
Since you are not allowed to use the string library, you should write your own version of strstr
and use that.
Here is a simple yet conforming implementation:
char *my_strstr(const char *s1, const char *s2) {
for (;;) {
for (size_t i = 0;; i++) {
if (s2[i] == '\0')
return (char *)s1;
if (s1[i] != s2[i])
break;
}
if (*s1++ == '\0')
return NULL;
}
}
You then use this function this way:
if (my_strstr(input_array, search_array)) {
printf("string was found\n");
} else {
printf("string was not found\n");
}
Upvotes: 1
Reputation: 21
You need some string comparison loop, like that of which you can find in strcmp
or strcspn
. This is assuming you use a terminal value like C strings; if you use some length field you'll need to make adjustments to the loops to account for those clearly. Here are some examples:
int strcmp(char const *x, char const *y) {
while (*x && *x == *y) {
x++;
y++;
}
return ((unsigned)*x > (unsigned)*y) - ((unsigned)*x < (unsigned)*y);
}
size_t strcspn(char const *x, char const *y) {
char const *x_ = x;
while (*x_) {
for (char const *y_ = y; *y_; y_++) {
if (*x_ == *y_)
return x_ - x;
}
x_++;
}
return x_ - x;
}
Upvotes: 2