提问人:user22869055 提问时间:11/8/2023 最后编辑:Vlad from Moscowuser22869055 更新时间:11/8/2023 访问量:128
如何在 C 中只计算一个句点?
How to count only a period in C?
问:
我只需要计算字符串中的句点 (.)。为此,我使用了库中的函数。我不想计算昏迷(,),也不想计算感叹号(!ispunct
ctype.h
我怎样才能只计算一个周期?
当我使用 ctype 库中的函数时,我的程序会计算句点 (.)、彗号 (,) 和感叹号。ispunct
答:
-1赞
AKX
11/8/2023
#1
写你自己的:isdot
int isdot(char c) {
return c == '.';
}
评论
1赞
Chris
11/8/2023
请注意,像 、 等这样的函数将字符作为 :ispunct
isdigit
int
int ispunct(int ch) { ... }
2赞
AKX
11/8/2023
大概是要考虑,但我认为这在这里并不重要。EOF
0赞
Chris
11/8/2023
如果函数采用指向其中一个库函数的函数指针,并改为提供此函数,则使用相同的签名将避免出现警告。
0赞
AKX
11/8/2023
确定。如果需要,OP 可能会在这一点上解决这个问题。
1赞
David C. Rankin
11/8/2023
@Chris始终值得注意的是宏参数,即使它被键入为“必须具有 or 的值”ctype.h
int
unsigned char
EOF
"
5赞
Chris
11/8/2023
#2
如果没有做你需要它做的事情,就不要使用它。只需检查是否与 相等。ispunct
'.'
size_t count_periods(const char *s) {
size_t count = 0;
for (size_t i = 0; s[i]; i++) {
if (s[i] == '.') count++;
}
return count;
}
-1赞
Vlad from Moscow
11/8/2023
#3
在这种情况下,标头中声明了标准的 C 函数。strchr
<string.h>
您可以编写一个单独的函数来计算字符串中的指定字符,例如
#include <string.h>
size_t count_char( const char *s, char c )
{
size_t n = 0;
for ( ; ( s = strchr( s, c ) ) != NULL; ++s )
{
++n;
}
return n;
}
该函数可以像
size_t n = count_char( "First statement. Second statement.", '.' );
printf( "There are %zu periods.\n", n );
给你。
#include <stdio.h>
#include <string.h>
size_t count_char( const char *s, char c )
{
size_t n = 0;
for (; ( s = strchr( s, c ) ) != NULL; ++s)
{
++n;
}
return n;
}
int main( void )
{
size_t n = count_char( "First statement. Second statement.", '.' );
printf( "There are %zu periods.\n", n );
}
程序输出为
There are 2 periods.
使用该函数,您可以计算字符串中的任何字符。
下一个:如何检查输入是否为 char
评论
foo == '.'
ispunct(c)
c == '.'
ispunct
:“检查给定字符是否为按当前 C 语言环境分类的标点符号。默认的 C 语言环境对字符进行分类!#$%&'()*+,-./:;<=>?@[\]^_
'{|}~
作为标点符号。ispunct
==