首页 > 试题广场 >

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

[编程题]字符串最后一个单词的长度
  • 热度指数:1475062 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾

输入描述:

输入一行,代表要计算的字符串,非空,长度小于5000。



输出描述:

输出一个整数,表示输入字符串最后一个单词的长度。

示例1

输入

hello nowcoder

输出

8

说明

最后一个单词为nowcoder,长度为8   
#include <iostream>
#include <string>

using namespace std;

int main(){
    string a;
    while(cin>>a){        
    }
    cout<<a.length();
    return 0;
}

发表于 2016-09-10 20:40:14 回复(0)
更多回答
推荐
/*使用动态数组来做,输入的字符串依次存入数组中,
最后返回数组中最后一个元素(字符串)的长度*/
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main(){
	string input;
	vector<string>arr;
    while(cin>>input){
    	arr.push_back(input);
	}
	cout<<arr[arr.size()-1].length()<<endl;		
	return 0;
}

编辑于 2016-08-29 14:07:27 回复(92)
 import java.util.*;
public class Main{
    public static int lengthOfLast(String str) {
        String[] s =str.split(" ");
        return s[s.length-1].length();
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String str = scan.nextLine();
            System.out.println(lengthOfLast(str));
        }
    }
}
java
-------------------------------------------
python
str = input().strip().split()
print(len(str[len(str)-1]))

编辑于 2017-10-14 10:19:42 回复(26)
// C++
//有些同学的答案没考虑到末尾有空格的情况,对于末尾有空格的都输出为0了。
//“hello world     ”依然输出5.
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    while(getline(cin,s)){
        int n=0,flag=1;
        for(int i=s.length()-1;i>=0;--i){//倒着计算
            if(flag && s[i]==' '){//如果末尾有空格,先清除末尾空格
                continue;
            }
            else if(s[i]!=' '){
                flag = 0;
                ++n;
            }
            else{
                break;
            }
        }
        cout << n << endl;
    }
    return 0;
}


编辑于 2016-04-13 11:09:48 回复(25)

python solution easy to understand:

a=input().split()
print(len(a[-1]) if len(a)>1 else len(a[0]))
编辑于 2017-09-06 15:35:03 回复(10)
a=input().split(" ")
print(len(a[-1]))
发表于 2021-08-18 11:08:00 回复(0)

 //输入流直接会记录最后一个字符串,因为单词之间是用空格隔开的
#include<iostream> #include<string> using namespace std; int main(){ string str; while(cin>>str); cout<<str.size()<<endl; return 0; }

编辑于 2016-09-01 22:17:34 回复(13)
#include <stdio.h>

int main(void)
{
    int len = 0;
    char c = '\0';
    
    while( (c = getchar()) != '\n' )
    {
        if( c == ' ' )
            len = 0;
        else
            len++;
    }
    
    printf( "%d\r\n", len );
    
    return 0;
}
发表于 2018-04-08 20:41:48 回复(8)
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] arr = line.split(" ");
        System.out.println(arr[arr.length-1].length());
        
    }
}

发表于 2016-03-25 11:25:37 回复(14)
import sys
for line in sys.stdin:
    a = line.split()
    print len(a[-1])
    
人生苦短,快用python,最近刚学的python,不要太简单奥!!
发表于 2016-03-20 20:23:33 回复(13)
//找到了半天没有我大JS的,上一个正确代码,给大家看看JS在牛客的输入输出,顺便吐槽一句
var readline = require('readline');
const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
});
rl.on('line', function(line){
   var tokens = line.split(' ');
    console.log(tokens[tokens.length-1].length);
});
发表于 2016-09-04 10:35:07 回复(4)
//最简单的方法就是,根本就不需要存储字符串,直接计算长度就可以了,也不需要动态的复杂的数据结构
#include <stdio.h>

int main()
{
	char ch;
	int n = 0;
	int flag = 0;

	while(1)
	{
		ch = getchar();
		if(ch == '\n'){
			break;
		}
		else if(ch != ' ')
		{
			if(flag == 0){
				n = 0;
				flag = 1;
			}
			n++;
		}
		else
		{
			flag = 0;
		}

	}
	printf("%d\n", n);
	return 0;
}


编辑于 2017-08-15 16:46:32 回复(8)
直接用c++提供的标准库函数进行解决。。方便,简单,代码量少少的,妈妈再也不用担心我不会码代码了!!!

#include <string>
#include <iostream>
 using namespace std;
intmain()
    {
    
    string input;
    string output_str;
    //cout<<"please input some words : "<<endl;
    while( getline(cin,input))
    {
        string::size_type pos=input.rfind(" ");
        output_str.assign(input,pos+1,input.size()-pos);
        cout<<output_str.size()<<endl;
    }
     
  return0; 
}
发表于 2016-01-19 10:01:39 回复(18)
我来个纯C的吧,仅供参考
#include<stdio.h>
#include<string.h>
void fun(char *array)
{
char *pnow,*plast;
pnow=plast=array;
//int len;
while(NULL!=*(++pnow))
{
if(*pnow==' ')
plast = pnow+1;
}
printf("%d\n",strlen(plast));
}
int main()
{
char a[1000];
while(NULL!=gets(a))
{
fun(a);
}
return 0;
}
发表于 2016-01-24 10:07:43 回复(5)
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char ch;
    int len = 0;
    while((ch = getchar())!= '\n')
    {
        if(ch == ' ')
        {
            len = 0;
        }
        else
        {
            len++;
        }
    }
    cout<<len<<endl;
    return 0;
}

思路就是:让它输入不为空格或者换行符时,才对输入进行++,空格就将字符串长度清零。
发表于 2019-09-09 18:59:03 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        String str = new Scanner(System.in).nextLine();
        System.out.print(str.length()-str.lastIndexOf(" ")-1);
    }
}
代码通过了,那些说要考虑最后一个单词后面的空格字符的,麻烦请审题

题目描述

计算字符串最后一个单词的长度,单词以空格隔开。 
发表于 2018-08-05 22:07:55 回复(3)
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    while (cin >> str) {
    }
    cout << str.length();
}
发表于 2023-09-18 16:41:45 回复(0)
var str=readline();
function fun(str){
    if(str.indexOf(' ')!=-1){
        var result=str.split(' ');
        return result[result.length-1].length;
    }else{
        return str.length;
    }
}
console.log(fun(str));
//javascript版
编辑于 2017-08-18 17:43:08 回复(4)
import java.util.Scanner;

public class Main {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String string=sc.nextLine();
        String[] array=string.split(" ");
        System.out.println(array[array.length-1].length());
    }
}
发表于 2020-04-07 22:26:04 回复(1)
发表于 2023-02-21 23:03:26 回复(1)
s = raw_input()
r = s.split(' ')
print len(r[-1])
发表于 2016-08-23 17:36:18 回复(2)
①类名必须是Main
②逻辑必须周全考虑null和空情况
③几次没通过也有点郁闷,很简单的代码单独去写就会出错 哈哈 需要多敲代码类 么么哒~

import java.util.Scanner;
public class Main{
public static int getLength(String str) {

		int length = 0;
		if (str != null && str.length() > 0) {
			String[] arr = str.split("\\s+");
			length = arr[arr.length - 1].length();
		} else {
			length = 0;
		}

		return length;

	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNextLine()) {
			String str = scanner.nextLine();
			int len = getLength(str);
			System.out.println(len);
		}

	}
}

发表于 2015-12-29 11:06:31 回复(2)