计算c char中每个单词的长度

时间:2016-06-02 09:12:18

标签: c pointers char

我有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();
}

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

3 个答案:

答案 0 :(得分:0)

这是对你的功能的一点修改。

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);

}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

试试这个:

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);  
    }
}
相关问题