【问题标题】:Why is my strchr not looping? I want it to output the number for however many times it sees '.' or ' !' or '?'为什么我的 strchr 不循环?我希望它输出数字,无论它看到多少次“。”要么 ' !'要么 '?'
【发布时间】:2020-09-27 20:26:03
【问题描述】:

我知道 strchr 只获得第一个实例。但是为什么我的循环不起作用。不管多少次'。要么 ' !'要么 '?'文中使用。一直输出3。

 //this finds number of sentences
    int Y = 0;
    while (ch != '\0');
    if(strchr(text,'.') != NULL)
        Y++;
    if(strchr(text,'!') != NULL)
        Y++;
    if(strchr(text,'?') != NULL)
        Y++;

【问题讨论】:

  • while (ch != '\0'); 是无限循环。 (提示:看;
  • 使用大括号。总是。几年后,如果您决定在某些情况下不使用大括号,那很好,但现在,总是 while (...) { if (...) { } }
  • strchr 不循环。它返回一个指向匹配的指针。如果您希望某些内容被递增并用作循环中的条件,您可能希望获取 strchr 返回的值并将其递增。

标签: c loops char c-strings strchr


【解决方案1】:

对于初学者来说,似乎有一个错字

while (ch != '\0');
                 ^^^ 

无论如何这个代码sn-p

int Y = 0;
while (ch != '\0');
if(strchr(text,'.') != NULL)
    Y++;
if(strchr(text,'!') != NULL)
    Y++;
if(strchr(text,'?') != NULL)
    Y++;

没有意义,因为目标字符的搜索总是从text的开头开始。

如果对每个目标符号使用单独的函数调用,则函数 strchr 不适合此任务。

在这种情况下,使用此函数您需要三个单独的循环,每个循环一个目标符号。

这是一个演示程序,展示了如何使用另一个字符串函数 strcspn 来执行任务。

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

size_t count_symbols( const char *s, const char *delim )
{
    size_t n = 0;

    while ( *s )
    {
        if ( *( s += strcspn( s, delim ) ) )
        {
            ++n;
            ++s;
        }           
    }

    return n;
}

int main(void) 
{
    const char *s = "Firt. Second? Third! That is all.";

    printf( "%zu\n", count_symbols( s, ".!?" ) );

    return 0;
}

程序输出是

4

【讨论】:

    【解决方案2】:
    size_t count(const char *haystack, const char *needle)
    {
        size_t cnt = 0;
    
        while(*haystack)
        {
            if(strchr(needle, *haystack++)) cnt++;
        }
        return cnt;
    }
    
    int main(void)
    {
        printf("%zu\n", count("Hwedgdf,.???,,,,.h.rtfdsg....dfsdgfs?gdfg//..? //.", ".?"));
    }
    

    https://godbolt.org/z/fLUsWz

    【讨论】:

    • 为什么是DV?有什么解释吗?
    • 只有代码的答案通常会因为没有试图解释你在做什么而被否决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2013-07-22
    • 2010-12-08
    • 1970-01-01
    • 2011-01-15
    • 2023-02-21
    • 2019-04-07
    相关资源
    最近更新 更多