计算字符串最后一个单词的长度,单词以空格隔开。-笔试面试资料
这是qklbishe.com第6527 篇笔试面试资料
提供答案分析,通过本文《计算字符串最后一个单词的长度,单词以空格隔开。-笔试面试资料》可以理解其中的代码原理,这是一篇很好的求职学习资料
本站提供程序员计算机面试经验学习,笔试经验,包括字节跳动/头条,腾讯,阿里,美团,滴滴出行,网易,百度,京东,小米,华为,微软等互联网大厂真题学习背诵。
答案:
计算字符串最后一个单词的长度,单词以空格隔开。
/*使用动态数组来做,输入的字
查看全部
2016-08-29 14:07:27 回复(82)
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 回复(22)
Python
华科平凡
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 回复(9)
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 回复(9)

// 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 回复(18)
import sys for line in sys.stdin: a = line.split() print len(a[-1])
人生苦短,快用python,最近刚学的python,不要太简单奥!!
2016-03-20 20:23:33 回复(11)
//输入流直接会记录最后一个字符串,因为单词之间是用空格隔开的#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 回复(10)
C/C++
__Shepherd
#include <stdio.h>
int main(void)
{
int len = 0;
char c = ‘