zoukankan      html  css  js  c++  java
  • 输入一个字符串,统计其中单词的个数

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<ctype.h>
     4 
     5 int word_cnt(char *str);
     6 void word_print(char *str, int beg, int end);
     7 //提取单词
     8 void word_split(char *str);
     9 
    10 int main()
    11 {
    12     char str[128];
    13     //int cnt = 0;
    14     gets_s(str,128);
    15     //cnt = word_cnt(str);
    16     //printf("count = %d
    ",cnt);
    17     word_split(str);
    18     system("pause");
    19     return 0;
    20 }
    21 
    22 int word_cnt(char *str)
    23 {
    24     int cnt = 0;
    25     int i = 0;
    26     while(str[i] != '')
    27     {
    28         //根据单词末尾判断
    29         if(isalnum(str[i]) && (str[i+1] == ' ' || str[i+1] == ''))
    30             ++cnt;
    31         //根据单词开头判断
    32         //if(isalnum(str[i]) && (i == 0 || i != 0 && str[i-1] == ' '))
    33         ++i;
    34     }
    35     return cnt;
    36 }
    37 
    38 void word_print(char *str, int beg, int end)
    39 {
    40     while(beg <= end)
    41     {
    42         putchar(str[beg]);
    43         beg++;
    44     }
    45     printf("
    ");
    46 }
    47 
    48 void word_split(char *str)
    49 {
    50     int cnt = 0;//记录单词的个数
    51     int i = 0;//下标
    52     int word_beg, word_end;//一个单词的开始、终止下标
    53 
    54     while(str[i] != '')
    55     {
    56         //找到单词的开头
    57         while(str[i] && !(isalnum(str[i]) && (i== 0 || i != 0 && str[i-1] == ' ')))
    58             ++i;
    59         if(str[i] == '')
    60             break;
    61         word_beg = i;
    62 
    63         ++cnt;
    64         //找到单词的结尾
    65         while(!(isalnum(str[i]) && (str[i+1] == '' || str[i+1] == ' ')))
    66             ++i;
    67         word_end = i;
    68         ++i;
    69         printf("%dth:  ",cnt);
    70         word_print(str,word_beg,word_end);
    71     }
    72 }
  • 相关阅读:
    C# 如何得到局域网中的计算机名?
    设计模式之Factory(转帖)[学习用]
    byte类型特殊的地方
    原码、反码和补码
    由Public key生成Public key token
    .Net位运算符&,|,!,^,<<,>>
    强命名程序集,签名,延迟签名
    把16进制字符转换成byte数组
    SHA1哈希算法
    .NET工具篇(四)—SN.EXE
  • 原文地址:https://www.cnblogs.com/cpsmile/p/4776821.html
Copyright © 2011-2022 走看看