计算并打印句子中每个单词的长度

counting and printing the length of each word in a sentence

本文关键字:单词 打印 句子 计算      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <cctype>
size_t countwords(const char *);
using namespace std;
int main()
{
    char a[] =  "Four score and seven years ago";
    cout << countwords(a);
    return 0;
}
size_t countwords( const char *s )
{
    size_t count = 0;
    while ( *s )
    {
        while ( isspace( *s )) ++s;
        if ( *s ) ++count;
        while ( isalnum( *s )) ++s;
    }

    return ( count );
}

我唯一缺少并且不知道如何执行的是打印句子中每个单词的长度。我需要我的函数来打印单词,除了返回字数统计外,它的长度并排。并且还要打印平均字符数。因此,例如,如果句子是"四分",我需要:

Four 4
scores 5
average: 4.5

如果你有C++11,你可以用<regex>来做到这一点。 请注意,一些编译器在这方面还不是很合规,但VC++12(VS2013(似乎做得很好,GCC即将到来。 这是整个程序:

#include <iostream>
#include <string>
#include <functional>
#include <regex>
int main() {
    std::string input("Four score and seven years ago");
    std::regex exp(R"([w]+)");
    int matches = 0, lengthSum = 0;
    std::for_each(
        std::sregex_token_iterator(input.begin(), input.end(), exp),
        std::sregex_token_iterator(),
        [&](std::ssub_match sm) {
            std::cout << sm << ": " << sm.str().size() << std::endl;
            matches++;
            lengthSum += sm.str().size();
        });
    std::cout << "Average: " << static_cast<float>(lengthSum) / matches << std::endl;
}

考虑这一行...

while ( isalnum( *s )) ++s;

在开始之前,s指向新单词的第一个字符。之后,它指向该新单词之后的第一个字符。如果我们捕捉到这两个指针...

const char *wordbegin = s;
while ( isalnum( *s )) ++s;
const char *wordend   = s;

您有指向原始字符串的指针来标识单词。若要获取单词的长度,可以从结束指针中减去开始指针。要输出单词(使用类似的 C 样式代码(,可以逐个字符遍历该范围。

为避免该循环,您可以暂时将指向的结束字符更改为 null,然后在打印后再次更改回来。 [对不起 - 想起我们使用const之前的旧日子]。

您还可以使用 std::string 的构造函数之一来复制和存储该单词,然后可以使用 length 方法来读取其长度。

未经测试:

size_t countwords( const char *s )
{
    size_t count = 0;
    size_t total_length = 0;
    while ( *s )
    {
        while ( isspace( *s )) ++s;
        if ( *s )
        {
            ++count;
            size_t word_length = 0;
            while ( isalnum( *s ))
            {
                std::cout << *s;
                word_length++;
                ++s;
            }
            std::cout << 't' << word_length << std::endl;
            total_length += word_length;
        }
    }
    std::cout << "average: " << ( count == 0 ? 0.0 : static_cast<double>( total_length ) / count )
              << std::endl; 
    return ( count );
}

while()中的伪代码

if issapce() s++ print count count=0;
else count++ s++;

数字和字母没有区别。

#include <iostream>
#include <vector>
#include <sstream>

int main() {
    std::string line =  "Four score and seven years ago";
    std::vector<std::string> words;
    std::istringstream iss(line);
    std::string word;
    while( iss>>word ){
        words.push_back(word);
    }
    double sum = 0;
    for(int i=0; i<  words.size(); ++i){
        std::cout<<words[i]<<" "<<words[i].size()<<std::endl;
        sum += words[i].size();
    }
    std::cout<< "average:"<< sum/words.size()<<std::endl;
    return 0;
}

注意:count 应该是 unsigned int 类型,而不是 size_t

您可以像这样编辑代码:

size_t countwords( const char *s )
{
    char *tmpWord = (char*) malloc(sieof(char)*strlen(s));
    int tmpLength = 0;
    while ( *s )
        {
            tmpLength = 0;
            while ( isspace( *s )) ++s;
            do{
                tmpWord[tmpLength++] = *s;
                ++s;
            }while(!isspace(*s));
            if ( *s ){ 
                ++count;
                printf("n%s %d",tmpWord,--tmpLength);
            }
            while ( isalnum( *s )) ++s;
        }
free(tmpWord);
}