C:如何读取多个字符串片段并打印 #of 片段和 #of 字符



所以我有一个输入: 啊 啊啊 啊 啊 啊 啊

(每组为1个片段(

我想要一个输出: 阅读 6 个片段,共 55 个字符

我该怎么做, 谢谢!

一个简单的方法:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int fragments = 0, characters = 0, in_fragment = 0, c;
while ((c = getchar()) != EOF) {
if (!isspace(c)) {
++characters;
if (!in_fragment)
++fragments;
}
in_fragment = !isspace(c);
}
printf("%d fragments read, %d characters in totaln",
fragments, characters);
return EXIT_SUCCESS;
}

在 Linux 中尝试如下:

$ gcc -Wall --pedantic test.c
$ echo "aaaaaaaaaa aaaaaa aaaaaaaaaa aaaaaaa aaaaaaaaaaa aaaaaaaaaaa" | ./a.out
6 fragments read, 55 characters in total

在窗口中应该是类似的

这是一种通过计算 no. 空格的方法,然后从 no 中扣除它们。 字符数:

#include<stdio.h>
#include<ctype.h>
#define MAX 100
#define IN 0        //INSIDE A FRAGMENT
#define OUT 1 //OUTSIDE A FRAGMENT
int main()
{
int i=0;
char str[]= " aa aaa ";
int charCount=0;
int countFragment =0;
int pos=OUT;
while (str[i])
{
while((str[i]!=' ')&&(str[i]))
{
if(pos!=IN)
{
pos=IN;
++countFragment;
}
++charCount;
++i;
}
while (str[i]==' ')
{
if(pos!=OUT)
pos=OUT;
++i;
}
}
printf("FRAGMENT: %dn CHARACTERS: %d",countFragment,charCount);
return 0;
}

输出:

FRAGMENT: 2
CHARACTERS: 5

最新更新