首页 > 解决方案 > 在字符串 ( C ) 中最后一次出现 :: 之后打印所有内容的应用程序

问题描述

我正在尝试编写一个在最后一次出现 2 个冒号“::”之后打印所有内容的应用程序,所以如果它是 3 个“:::”,它就不算数。如果字符串是“He::ll::o”,它应该打印出“o”,如果它是“12312::233”,它应该打印出“233”,我必须使用一个我今天刚开始学习char* extract(char* input);的指针函数我有点不知所措。我也不允许导入库。这就是我到目前为止所拥有的。任何帮助表示赞赏。void extract2(char* input, char** output)C


int isCH(char c) {
  return (c != ':' && c != '\0');
}

char *extract(char *input){
    int state = 1;
    char *doubleColon;
    
    while(1){
        switch(state){
            case 1:
                if(isCH(*input))
                state = 1;
                if(*input == '\0')
                state = 2;
                if(*input == ':') // first colon
                state = 3;
            break;
            case 2:
                return doubleColon;
            break;
            case 3:
                if(isCH(*input))
                state = 1;
                if(*input == '\0')
                state = 2;
                if(*input == ':'){ // second colon
                state = 4;
                doubleColon = input;
                }
            break;
            case 4:
                if(isCH(*input))
                state = 1;
                if(*input == '\0')
                state = 2;
                if(*input == ':')
                state = 1;
                break;
        }
        input++;
    }
}

int main() {
    printf("End of String: %c", *extract("Ha::ll::o"));
} 

标签: cwhile-loopcountswitch-statementprintf

解决方案


更通用的功能。在最后一次出现任何分隔符后,它将返回指向剩余字符的指针。

char *extract(char *input, const char *del)
{
    char *last = NULL, *current = NULL;
    size_t delLength = strlen(del);

    if(input && del && *del)
    {
        do
        {
            if(current)
            {
                last = current + delLength;
                input = last;
            }
        }while((current = strstr(input, del)));
    }
    return last;
}

int main() {
    char *res;
    printf("End of String: %s\n", (res = extract("Ha::ll::o", "::")) ? res : "Not found");
    printf("End of String: %s\n", (res = extract("Ha::ll::o", ":ll:")) ? res : "Not found");
    printf("End of String: %s\n", (res = extract("", "::")) ? res : "Not found");
    printf("End of String: %s\n", (res = extract(NULL, "::")) ? res : "Not found");
} 

https://godbolt.org/z/EbM1cP


推荐阅读