OJ题:字符串最后一个单词的长度

来源:互联网 发布:matlab字符矩阵cell 编辑:程序博客网 时间:2024/06/03 18:40

题目描述

计算字符串最后一个单词的长度,单词以空格隔开。


输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
输入例子:
hello world
输出例子:
5
程序如下:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void){    char str[5000] = {0};    int count = 0 ,start;    gets(str);    const int str_length =  strlen(str);    start = str_length - 1 ;    while(start >= 0)    {        if(str[start] == ' ')            break ;        count++ ;        start-- ;    }    printf("%d",count);    return 0 ;}
题目陷阱,肯定会有同学用scanf()去输入字符串,这里应当使用gets();gets() 和scanf()的区别在于输入的字符串是否中间有空格:对于前者,只有遇到"\n"时才停止输入,而对于后者,出现"\n"或空格都停止输入。



0 0
原创粉丝点击