【问题标题】:Writing a function that converts "12#abcd#09bla" into "abcd"编写将“12#abcd#09bla”转换为“abcd”的函数
【发布时间】:2015-03-11 20:51:06
【问题描述】:

所以经过大量的反复试验,我做到了:

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

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

【问题讨论】:

  • 更适合代码审查?
  • 我更倾向于将其视为12(abcd)09bla12"abcd"09bla 来吸引您的注意力。
  • for(i=100;i&gt;0;i--)?????你必须去for(i=99;i&gt;=0;i--)!!!!!
  • @IdeaHat 而不是12(abcd(09bla?
  • @NickT 是的,不平衡的括号是我决定加上引号的原因。阅读到 delim,复制到 delim,打印 0,完成。

标签: c string function


【解决方案1】:

以下是仅使用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 */
}

【讨论】:

  • 这个也很好用,谢谢!它的问题是它有很多我还不知道的元素,我正在努力为明天的考试而学习,所以 - 没有时间谷歌它的每一行。 :D
  • 如果您对代码有任何疑问,请随时提出。同时,我会添加一些cmets。
  • 非常感谢!我有很多问题,但没有时间,我必须做一堆函数,然后继续排序算法和处理文件。我有大约 20 个小时来完成这一切,所以是的。我会将此页面添加为书签,谢谢您的努力!我希望我能投票,但它说我没有足够的声誉。
  • @slamdunker 你现在应该可以投票了。
【解决方案2】:
void hashtag(char *S, char *P){
    sscanf(S, "%*[^#]#%[^#]", P);
    puts(P);
}

【讨论】:

  • 嗯,这...更容易。没听说过sscanf。现在想想,strchr 和 strrchr 也可以做到的,对吧?
  • @slamdunker 你可以使用strchrstrrchr 重写你的代码。我的代码与此完全不同。
  • strrchr 优于 for(i=99;i&gt;=0;i--)
  • 我可以提供一个链接,了解 sscanf 如何解决这些类型的问题吗?我可以找到数百万其他人,我想我理解其中的 %[^#] 部分,但不完全理解其余部分。
  • %*[^#] 的一部分以跳过直到# 的字符。 %[^#] 读取最多# 的字符。
猜你喜欢
  • 2014-05-22
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多