Max Jones
Max Jones

Reputation: 135

Return pointer of start of substring in string with restrictions (C)

So I know this is really simple (Or at least think so), I just am not familiar enough to C to see it.

Question: Return a pointer to the first character of the first occurrence of substring in the given string or NULL if substring is not a substring of string. Note: An empty substring ("") matches any string at the string's start.

Starter Code:

char *find_substr(char *string, char* substring) {
   return 0;
}

Restrictions: This is a ungraded (Which is why I am here) review of C assignment at my college, so it has some pretty weird restrictions:

  1. You can not use array indexing

  2. You can not use integers

  3. You can not #include <string.h> or anything else

What I have: Basically nothing, I can think of 100 diffrent ways to do this without the restriction, but I am not used to using pointers in code and this is really stumping me.

Upvotes: 0

Views: 824

Answers (1)

Challenger5
Challenger5

Reputation: 1064

Rather than maintaining indexes into the string, you can perform the check using pointer arithmetic directly. This approach uses a doubly-nested loop, where for each position in the string it checks if the substring starts there.

#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>

bool starts_with(char *str, char *prefix) {
    while (*str == *prefix) {
        if (*prefix == '\0') {
            // an empty string is a prefix of any string
            return true;
        } else if (*str == '\0') {
            // no non-empty strings are prefixes of the empty string
            return false;
        }
        str++;
        prefix++;
    }
    // one string is not a prefix of the other if their first characters are not the same
    return false;
}

char *find_substr(char *str, char *sub) {
    for (char *p = str; *p; p++) {
        if (starts_with(p, sub)) {
            return p;
        }
    }
    return NULL;
}

Upvotes: 3

Related Questions