编写一个将“12#abcd#09bla”转换为 "abcd" 的函数

Writing a function that converts "12#abcd#09bla" into "abcd"

经过大量的反复试验,我是这样做的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/*Prototype of a hashtag function*/
void hashtag(char *,char *);

int main()
{
    /* Declaration of strings S and P*/
    char S[100], P[100]="";

    /*Getting the string S from a keyboard*/
    printf("Unesi string S: ");
    gets(S);

    /*Calling "hashtag"*/
    hashtag(S,P);
}
/*Hashtag function*/
void hashtag(char *S,char *P)
{
    /*Finding the position of 2 #'s in string S*/
    int i, t1, t2;
    for(i=0;i<100;i++)
    {
        if(S[i]=='#')
        {
            t1=i;
            break;
        }
    }
    for(i=100;i>0;i--)
    {
        if(S[i]=='#')
        {
            t2=i;
            break;
        }
    }
    /*"Filling" the empty string P with the text in between #'s*/
    int k;
    for(i=t1+1,k=0;i<t2,k<(t2-t1-1);i++,k++)
    {
        P[k]=S[i];
    }
    puts(P);
}

为什么我有这种可怕的感觉,觉得这太复杂了?我有一种感觉,找到确切的位置是没有必要的,而且它可以比这更简单。

void hashtag(char *S, char *P){
    sscanf(S, "%*[^#]#%[^#]", P);
    puts(P);
}

以下是仅使用 strchr 的方法。此函数不输出 p,但在失败时输出 returns -1,即当函数无法找到两个 # 符号时。

int hashtag(const char *s, char *p)
{
    const char *end;

    /*
     * We want to have s point right after the first #. strchr() makes
     * s point to the first # or NULL if no # is found. In the if, we
     * check for that and sneakingly increment s so it points right
     * after the first #.
     */
    s = strchr(s, '#'); 
    if (s++ == NULL)
        return (-1);

    /* this makes end point to the second #, like before */
    end = strchr(s, '#');
    if (end == NULL)
        return (-1);

    /* copy the text between the two # signs into p */
    memcpy(p, s, end - s - 1);
    p[end - s] = '[=10=]'; /* terminate p with a '[=10=]' as it is a string */

    return (0); /* success */
}