简体   繁体   English

返回带限制的字符串中 substring 的开始指针 (C)

[英]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.所以我知道这真的很简单(或者至少是这么认为),我只是不够熟悉 C 才能看到它。

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.问题:如果 substring 不是字符串的 substring,则返回给定字符串中第一次出现 substring 或 NULL 的第一个字符的指针。 Note: An empty substring ("") matches any string at the string's start.注意:空的 substring ("") 匹配字符串开头的任何字符串。

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:限制:这是我大学 C 作业的未评分(这就是我来这里的原因)复习,因此它有一些非常奇怪的限制:

  1. You can not use array indexing您不能使用数组索引

  2. You can not use integers你不能使用整数

  3. You can not #include <string.h> or anything else你不能 #include <string.h> 或其他任何东西

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.我有什么:基本上什么都没有,我可以想出 100 种不同的方法来不受限制地做到这一点,但我不习惯在代码中使用指针,这真的让我很困惑。

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.这种方法使用双重嵌套循环,对于字符串中的每个 position,它检查 substring 是否从那里开始。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM