zoukankan      html  css  js  c++  java
  • C语言统计一个字符串中单词的个数

    假定每一个单词用空格隔开。

    样例:

    输入:how are you!

    输出:3

    两种方法:


    一:

    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 20
    
    int main()
    {
    	char str[SIZE]={''};
    	int count=0;
    	printf("please input the string
    ");
    	gets(str);
    	puts(str);
    	int length = strlen(str);
    	for (int i=0;i<length;i++)
    	{
    		//推断是不是空格不是的话在while里面i++运行推断到下一个空格的出现或是结束
    		if(str[i]!=' ')
    		{
    			count++;
    			while(str[i]!=' '&&str[i]!='')
    			{
    				i++;
    			}
    		}
    	}
    	printf("%d
    ",count);
    	return 0;
    
    }
    

    另外一种:

    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 20
    
    int main()
    {
    	char str[SIZE]={''};
    	int count=0;
    	int flag=0;
    	printf("please input the string
    ");
    	gets(str);
    	puts(str);
    	int length = strlen(str);
    	for (int i=0;i<length;i++)
    	{
    		//推断是不是空格。是的话flag=0,
    		//不是的话推断前面是不是空格即flag是否等于0。
    		//是空格的话说明是新单词的開始
    		if(str[i]==' ')
    		{
    			flag=0;
    		}
    		else
    		{
    			if(flag==0)
    			{
    				count++;
    				flag=1;
    			}
    		}
    	}
    	printf("%d
    ",count);
    	return 0;
    
    }
    


  • 相关阅读:
    并发工具类的使用 CountDownLatch,CyclicBarrier,Semaphore,Exchanger
    多线程按顺序执行3个方法
    读写锁事例
    使用AQS自定义重入锁
    java 几种锁实现
    Nginx 安装
    Windows 安装mysql
    day--14前端(HTML、CSS)
    day13--开发堡垒机
    day12--python操作mysql
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5377310.html
Copyright © 2011-2022 走看看