【问题标题】:C: How to read multiple string fragments and print #of fragments and #of chars [closed]C:如何读取多个字符串片段并打印#of片段和#of chars [关闭]
【发布时间】:2019-02-18 20:18:48
【问题描述】:

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

(每组a为1个片段)

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

我该怎么做, 谢谢!

【问题讨论】:

标签: c string algorithm


【解决方案1】:

这是一种通过数数来做到这一点的方法。的空间,然后从没有扣除它们。字符数:

  #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: %d\n CHARACTERS: %d",countFragment,charCount);
       return 0;
  }

输出:

 FRAGMENT: 2

 CHARACTERS: 5

【讨论】:

  • 如果你只是要遍历字符串,为什么要调用 strlen 呢?只需检查 NUL。
  • 我认为@Roflcopter4 指的是在不提前计算长度的情况下做一些更像while (str[i] != '\0') 的事情。否则你会遍历字符串两次;当循环完成时,i 是字符串的长度。
  • @ChronoKitsune 我完全错过了!!
  • @chux 包括在内!
  • @chux 非常感谢,已解决!我需要做很多事情。
【解决方案2】:

一个简单的方法:

#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 total\n",
           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

在windows中应该是类似的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多