编写一个转换" 12#abcd#09bla"进入" abcd"

时间:2015-01-13 19:24:03

标签: c string function

因此经过大量的反复试验,我就这样做了:

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

为什么我有这种可怕的感觉,这太荒谬了?我有一种感觉,找到确切的位置是不必要的,并且它可以做得比这简单得多。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

以下是仅使用strchr的方法。此函数不输出p,但在失败时返回-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] = '\0'; /* terminate p with a '\0' as it is a string */

    return (0); /* success */
}