gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:40:09 27 4
gpt4 key购买 nike

我写了一个代码,它接受一个句子并输出一行中的每个单词。但我也想在它旁边写下每个单词的大小。

输入:

Hi my name is

当前输出:
Hi
my
name
is

所需输出:
Hi(2)
my(2)
name(4)
is(2)

我当前的代码:
#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;
}

我怎样才能做到这一点?

最佳答案

为了完整起见,另一种方法是在一次调用中读取整个输入,然后对其进行标记:

#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;
}

由于从未显式使用读取缓冲区,因此以下变化也是可能的:
#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;
}

关于c - 如何找到字符串中每个单词的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58926462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com