【问题标题】:Counting length of each words in c char计算c char中每个单词的长度
【发布时间】:2016-06-02 09:12:18
【问题描述】:

我有 char* 指针并试图计算每个单词的长度。但我在调试器中没有得到任何结果(只是空白)。无论我改变什么,我都没有得到任何结果。代码:

void wordsLen(char* text, int* words, int n)
{
    int i, count = 0, s = 0;
    //words[countWords(text)]; // not important

    for (i=0; i < n; i++)
    {
        if (text[i] != ' ')
        {
            count++;

        }
        else 
        {
            printf("%d",count);
        }
        printf("%d",count);//if I add this it types the count from 1 to the end
    }
}

我尝试插入这个数组:

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

#define N 100
void main()
{
    char t[] = "hello my name is.";
    int cum[N];
    wordsLen(t, cum, strlen(t));
    getch();
}

由于没有得到任何结果,我想知道为什么,计算单词长度的代码有什么问题吗?比如计算单词的长度有好处吗?还是我需要改变一些东西。

【问题讨论】:

  • wordsLen 是否有值?
  • 另外,words[countWords(text)]; 是什么?
  • C 还是 C++?有不同的语言
  • countwords(text) 返回 text* 和 c++ 中的单词数,如有错误请见谅。
  • 您发布了由于多种原因无法编译的代码,然后在人们试图提供帮助时开始对其进行修改。我不赞成,vtc 是“不清楚”:(

标签: c pointers char


【解决方案1】:

这里是对你的函数的一点修改。

void wordsLen(char* text, int* words, int n)
{
    int i, count = 0, s = 0;

    for (i=0; i < n; i++)
    {
        if (text[i] != ' ')
        {
            count++;
        }
        else 
        {
            printf("%d",count);
            count = 0;
        }
    }
    printf("%d", count);

}

【讨论】:

  • 这是不正确的,因为我认为最后一个字没有计算在内。
  • @kevin Wallis 我在循环结束后添加了一个打印语句,它将打印最后一个单词的计数。
【解决方案2】:

这里有一些计算单词和长度的代码:

void addWord(int* numberOfWords, int* count) {
    *numberOfWords = *numberOfWords + 1;
    *count = 0;
}

void print(int numberOfWords, int count) {
    printf("number of words %d \n", numberOfWords);
    printf("word length %d \n", count);
}

void wordsLen(char* text, int* words, int n)
{
    int i = 0;
    int count = 0;
    int numberOfWords = 0;
    //words[countWords(text)]; // dynamicly set the length

    for (i = 0; i < n; i++)
    {
        char ch = text[i];
        if (ch != ' ')
        {
            count++;
        }

        if (count > 0 && (ch == ' ' || (i == n - 1)))
        {
            print(numberOfWords + 1, count);
            addWord(&numberOfWords, &count);
        }
    }
}

【讨论】:

    【解决方案3】:

    试试这个:

    void wordsLen(char* text, int* words, int n) 
    { 
        int i, count = 0, s = 0; 
        //words[countWords(text)]; // not important 
    
        for (i=0; i <= n; i++) 
        { 
            if (text[i] != ' ' && text[i] != '\0') 
            {
                count++; 
            }
            else 
            { 
                printf("%d ",count);  
                count = 0;            
            }
            //printf("%d",count);  
        }
    }
    

    【讨论】:

    • 它不会打印最后一个单词的计数。
    • 请注意
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2017-10-09
    • 2019-11-14
    • 1970-01-01
    • 2021-04-19
    • 2015-01-03
    相关资源
    最近更新 更多