题解 | #字符串最后一个单词的长度#

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

http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); // 创建 Scan 实例对象
        String str = scan.nextLine(); // 获取要计算的字符串
        char[] chrs = str.toCharArray(); // 将字符串转换为 char 类型的数组
        int ans = chrs.length; // 定义一个整型变量,用于存放最终的返回结果
        for (int i = chrs.length - 1; i > -1; i--) {
            if (chrs[i] == ' ') {
                ans = chrs.length - 1 - i;
                break;
            }
        }
        System.out.println(ans);
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-20 16:09

相关推荐

asdasdasda...:19岁,不容易啊可能升个本会好点,现在学历歧视太严重了
点赞 评论 收藏
分享
想按时下班的我在等o...:我投测试也是这个情况,不知道咋办了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务