c - C语言计算字符串中每个单词的长度的程序

标签 c c-strings word

我正在编写一个程序来计算字符数组中每个单词的长度。我想知道你们是否可以帮助我,因为我现在已经为此苦苦挣扎了至少两个小时,而且我不知道如何正确地做到这一点。 它应该是这样的:

(字母数)-(具有这么多字母的单词数)
2 - 1
3 - 4
5 - 1
等等

char tab[1000];
int k = 0, x = 0;

printf("Enter text: ");
fgets(tab, 1000, stdin);

for (int i = 2; i < (int)strlen(tab); i++)
{


    for (int j = 0; j < (int)strlen(tab); j++)
    {
        if (tab[j] == '\0' || tab[j]=='\n')
            break;
        if (tab[j] == ' ')
            k = 0;
        else k++;

        if (k == i)
        {
            x++;
            k = 0;
        }
    }
    if (x != 0)
    {
        printf("%d - %d\n", i, x);
        x = 0;
        k = 0;
    }

}



return 0;

最佳答案

通过使用两个 for 循环,您可以进行len**2 字符扫描。 (例如)对于长度为 1000 的缓冲区,不是进行 1000 次字符比较,而是进行 1,000,000 次比较。

如果我们使用字长直方图数组,这可以在单个 for 循环中完成。

基本算法与您的内部循环相同。

当我们有一个非空格字符时,我们增加当前长度值。当我们看到一个空格时,我们将直方图单元格(由长度值索引)增加 1。然后我们将长度值设置为 0。

下面是一些有效的代码:

#include <stdio.h>

int
main(void)
{
    int hist[100] = { 0 };
    char buf[1000];
    char *bp;
    int chr;
    int curlen = 0;

    printf("Enter text: ");
    fflush(stdout);

    fgets(buf,sizeof(buf),stdin);
    bp = buf;

    for (chr = *bp++;  chr != 0;  chr = *bp++) {
        if (chr == '\n')
            break;

        // end of word -- increment the histogram cell
        if (chr == ' ') {
            hist[curlen] += 1;
            curlen = 0;
        }

        // got an alpha char -- increment the length of the word
        else
            curlen += 1;
    }

    // catch the final word on the line
    hist[curlen] += 1;

    for (curlen = 1;  curlen < sizeof(hist) / sizeof(hist[0]);  ++curlen) {
        int count = hist[curlen];
        if (count > 0)
            printf("%d - %d\n",curlen,count);
    }

    return 0;
}

更新:

and i don't really understand pointers. Is there any simpler method to do this?

指针是 C 语言库中非常重要的 [基本] 工具,所以我希望您能尽快使用它们。

但是,转换 for 循环非常容易(删除 char *bp;bp = buf;):

改变:

for (chr = *bp++;  chr != 0;  chr = *bp++) {

进入:

for (int bufidx = 0;  ;  ++bufidx) {
    chr = buf[bufidx];
    if (chr == 0)
        break;

for 循环的其余部分保持不变。

这是另一个循环 [但是,没有编译器优化] 双重获取字符:

for (int bufidx = 0;  buf[bufidx] != 0;  ++bufidx) {
    chr = buf[bufidx];

这里是单行版本。请注意,这不是推荐的做法,因为 chr 内部 的嵌入式赋值 循环条件子句,但适用于说明目的:

for (int bufidx = 0;  (chr = buf[bufidx]) != 0;  ++bufidx) {

关于c - C语言计算字符串中每个单词的长度的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53418740/

相关文章:

c# - 如何在字符串末尾插入退格

c - 你将使用什么排序技术?

cat 终端,检查 usb 是否已移除(错误)?

c - 将 for 循环中的值存储到数组中

c - 访问/修改结构中的字符串数组

c - 为字符串动态分配内存

c - 我怎样才能终止系统()?

c - 用户自定义静态库与可重入性

c - char[] 的初始化并使用它。我不想使用 "string"

php - 在PHP中有没有一个工具可以获取一个词的所有派生词?