【问题标题】:To print only the first occurence of a substring in c仅打印 c 中第一次出现的子字符串
【发布时间】:2016-10-20 16:18:45
【问题描述】:

我是 C 新手。我有这样的代码

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

int i = 0;
int main()
{
    char text[] = "..... $it is beautiful : $yes you are correct....";
    char * sub = "$";
    char * ret = strstr(text, sub);

    if (ret != NULL)
    {
         printf("the statement is : %s", ret);
    }
}

我只想打印这部分代码:$it is beautiful。 有没有办法只打印那个语句?让我们假设这是全文的一部分,那么除了使用 strlen 之外还有什么想法吗? 当出现第二个$ 时不应该出现打印。这是我的基本要求

【问题讨论】:

  • 你现在得到什么印刷品?
  • $它很漂亮:$是的,你是对的....这是打印输出

标签: c substring


【解决方案1】:

这应该可行。

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

 int i=0;
 int main()
{
    char text[] = "..... $it is beautiful : $yes you are correct....";
    char* sub = "$";
    char* ret = strstr(text,sub);
    char *out = malloc(strlen(text)+1); //To make the solution generic

    if (ret!=NULL )
     {
         sscanf(ret, "$%[^$^:]", out);
         printf("the statement is : [%s] \n",out );
     }

     free(out);
}

【讨论】:

    【解决方案2】:

    根据您的输出要求使用strchr:$

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char text[] = "..... $it is beautiful : $yes you are correct....";
        char * ret = strstr(text, "$");
        if (ret != NULL) {
            char *colon;
            if (colon = strrchr(ret, ':'))
                *colon = '\0';
            printf("The statement is: %s", ret);
        }
        return 0;
    }
    

    输出

    声明是:$it is beautiful

    【讨论】:

    • @kaya 很高兴它有帮助。
    猜你喜欢
    • 2014-03-21
    • 2010-12-12
    • 2018-02-05
    • 2011-08-25
    • 1970-01-01
    • 2019-12-12
    • 2013-02-08
    相关资源
    最近更新 更多