简体   繁体   English

如何找到字符串中每个单词的长度?

[英]How to find the length of every word in a string?

I wrote a code that takes a sentence and outputs every each word in a line.我写了一个代码,它接受一个句子并输出一行中的每个单词。 But I also want to write the size of each word next to it.但我也想在它旁边写下每个单词的大小。

Input:输入:

Hi my name is

Current output:当前 output:

Hi
my
name
is

Desired output:所需的 output:

Hi(2)
my(2)
name(4)
is(2)

My current Code:我目前的代码:

#include <stdio.h>

#define MAX 100

int main(void) {

    int c = 0;
    size_t n = 0;

    printf("\n Enter a sentence.\n\n input: ");

    /* read up to 100 characters from stdin, print each word on a line */
    while (n < MAX && (c = getchar()) != EOF && c != '\n')
    {
        if (c == ' ')
            printf("\n");
        else
            printf("%c", c);
        n++;
    }
    printf("\n");

    if (n == MAX) /* read and discard remaining chars in stdin */
        while ((c = getchar()) != '\n' && c != EOF);

    return 0;
}

How can I do that?我怎样才能做到这一点?

For completeness a different approach reading the whole input in one call and then tokenising it:为了完整起见,一种不同的方法在一次调用中读取整个输入,然后对其进行标记:

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

#define MAX (100)

int main(void) 
{
  int result = EXIT_SUCCESS; /* Be optimistic. */ 
  char s[MAX +1];

  printf("\n Enter a sentence.\n\n input: ");

  /* read up to 100 characters from stdin, print each word on a line */

  if (NULL == fgets(s, sizeof s, stdin))
  {
    if (ferror(stdin))
    {
      perror("fgets() failed");
      result = EXIT_FAILURE;
    }
  }
  else
  {
    s[strcspn(s, "\r\n")] = '\0'; /* chop off carriage return, line feed, if any */

    for (char * pc = strtok(s, " "); NULL != pc; pc = strtok(NULL, " "))
    {
      printf("%s (%zu)\n", pc, strlen(pc));
    }
  }

  return result;
}

As the read buffer is never explicitly used the following variation is possible as well:由于从未显式使用读取缓冲区,因此也可能出现以下变化:

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

#define MAX (100)

int main(void) 
{
  int result = EXIT_SUCCESS; /* Be optimistic. */ 

  printf("\n Enter a sentence.\n\n input: ");

  {
  /* read up to 100 characters from stdin, print each word on a line */    
    char * pc = fgets((char[MAX+1]), MAX+1, stdin);
    if (NULL == pc)
    {
      if (ferror(stdin))
      {
        perror("fgets() failed");
        result = EXIT_FAILURE;
      }
    }
    else
    {
      pc[strcspn(pc, "\r\n")] = '\0'; /* chop off carriage return, line feed, if any */

      for (pc = strtok(pc, " "); NULL != pc; pc = strtok(NULL, " "))
      {
        printf("%s (%zu)\n", pc, strlen(pc));
      }
    }
  }

  return result;
}

Have one more variable and print out when you hit space.再有一个变量,当你点击空格时打印出来。

size_t len = 0;

/* read up to 100 characters from stdin, print each word on a line */
while (n < MAX && (c = getchar()) != EOF && c != '\n')
{
    if (c == ' ') {
        printf("(%u)\n", len);
        len = 0;
    }
    else {
        len++;
        printf("%c", c);
    }
    n++;
}

In addition to the good answer by @kiranBiradar , you may want to add an additional variable that allows you to track whether you are in-a-word reading characters or outside-a-word reading whitespace .除了@kiranBiradar的好答案之外,您可能还需要添加一个额外的变量,该变量允许您跟踪您是在单词内阅读字符还是在单词外阅读空格 (using a simple int value as a flag set to 1 (true) for in-word or 0 (false) not-in-word is all you need) This will allow you to ignore leading whitespace, multiple included whitespace, or trailing whitespace in your input, eg, if your input was similar to: (使用简单的int值作为设置为1 (true) 用于 in-word 或0 (false) not-in-word 的标志就是您所需要的)这将允许您忽略前导空格、多个包含的空格或尾随空格在您的输入中,例如,如果您的输入类似于:

"   my       dog   has      fleas   and my   cat has   none  "

Unless you are keeping track of the state of your read, whether you are in-word / not-in-word , you will be outputting multiple occurrences of "(0)\n" each time a whitespace character is read.除非您跟踪读取的 state ,否则无论您是in-word / not-in-word ,每次读取空白字符时都会输出多次出现的"(0)\n" By keeping a flag of whether you are in / not-in a word and setting it zero when you encounter your first whitespace after being in-word reading non-whitespace characters allows you to only output the length once on the first whitespace encountered.通过保留您是否在/不在一个单词中的标志并将其设置为零,当您在单词内读取非空白字符后遇到您的第一个空格时,您可以在遇到的第一个空格上仅 output 长度一次。

Additionally, conditioning your read on c != '\n' will skip outputting the length of the final word, unless you include additional code after you exit your read loop.此外,在c != '\n'上调节您的阅读将跳过输出最终单词的长度,除非您在退出阅读循环后包含其他代码。

Also by including <ctype.h> you have the isspace() macro available to check for all whitespace (eg, space, tab, newline, backspace, vertical-tab , etc...) It greatly simplifies your conditional checks.此外,通过包含<ctype.h>您可以使用isspace()宏来检查所有空格(例如, space, tab, newline, backspace, vertical-tab等...)它大大简化了您的条件检查。

Putting it altogether you could do:总而言之,您可以这样做:

#include <stdio.h>
#include <ctype.h>      /* for isspace() */

int main (void) {

    int c = 0, in = 0, len = 0;             /* char, in/out flag, length */

    fputs ("enter text: ", stdout);         /* prompt for text */
    fflush (stdout);                        /* (optional), but recommended */

    while ((c = getchar()) != EOF) {        /* loop reading chars until EOF */
        if (isspace (c)) {                  /* if input is space */
            if (in) {                       /* check if in-word */
                printf ("(%d)\n", len);     /* output (len) */
                len = 0;                    /* reset len zero */
                in = 0;                     /* set in flag zero (false) */
            }
            if (c == '\n')                  /* if space is \n */
                break;                      /* break read loop */
        }
        else {  /* if not whitespace */
            putchar (c);                    /* output char */
            len++;                          /* increment length */
            in = 1;                         /* set in flag 1 (true) */
        }
    }
}

( note: there is no reason to limit your read to n < MAX unless you simply want to arbitrarily limit your read of characters to the first 100-characters. There is no array being filled or other storage being occupied by the character c (aside from it's one byte). You could read billions if your input contained them) 注意:没有理由将您的读取限制为n < MAX ,除非您只是想任意将字符读取限制为前 100 个字符。字符c没有填充数组或占用其他存储空间(除了从它是一个字节)。如果你的输入包含它们,你可以读取数十亿)

Example Use/Output示例使用/输出

$ ./bin/getchar_word_len
enter text:      my       dog   has      fleas   and my   cat has   none
my(2)
dog(3)
has(3)
fleas(5)
and(3)
my(2)
cat(3)
has(3)
none(4)

Look over both answers and let either of us know if you have further questions.查看两个答案,如果您还有其他问题,请告诉我们中的任何一个。 If you are confused by the logic, take out an 8.5x11 sheet of paper and work through the logic of the loop for each character starting at the beginning of your input.如果您对逻辑感到困惑,请取出一张 8.5x11 的纸,并从输入的开头开始为每个字符完成循环的逻辑。 It will make sense by the time you work through the first word.当您完成第一个单词时,它就会变得有意义。

I was actually having this problem the other day and I figured out the problem with this solution前几天我实际上遇到了这个问题,我发现了这个解决方案的问题

#include <stdio.h>

#define MAX 100

int main(void) {

    int c = 0;
    size_t n = 0;

    printf("\n Enter a sentence.\n\n input: ");

    /* you've been gnomed */
#include <stdio.h>

#define MAX 100

int main(void) {

    int c = 0;
    size_t n = 0;

    printf("\n Enter a sentence.\n\n input: ");

    /* read up to 100 characters from stdin, print each word on a line */
    while (n < MAX && (c = getchar()) != EOF && c != '\n')
    {
        if (c == ' ')
            printf("\n");
        else
            printf("%c", c);
        n++;
    }
    printf("\n");

    if (n == MAX) /* read and discard remaining chars in stdin */
        while ((c = getchar()) != '\n' && c != EOF);

    return 0;
}
    while (n < MAX && (c = getchar()) != EOF && c != '\n')
    {
        if (c == ' ')
            printf("\n");
        else
            printf("%c", c);
        n++;
    }
    printf("\n");

    if (n == MAX) /* read and discard remaining chars in stdin */
        while ((c = getchar()) != '\n' && c != EOF);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM