0

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.

2
  • Do you have access to a copy of the book "The C Programming Language"? If you do look at section 5.6. Commented Jan 14, 2021 at 4:40
  • Sorry, not section 5.6, I meant section 5.5. Commented Jan 14, 2021 at 4:50

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

For such tasks, I find char *haystack, char *needle name informative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.