码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-08-18 23:02:04      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

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

输入描述

一行字符串

输出描述

整数N,最后一个单词的长度。

输入例子

hello world

输出例子

5

方法1
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        while(in.hasNextLine()) {
            String str = in.nextLine();
            String[]  array = str.split(" ");
            System.out.print(array[array.length - 1].length());
        }
        in.close();
    }
}

方法2

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        while(in.hasNextLine()) {
            String str = in.nextLine();
            System.out.print(findLastWordLength(str));
        }
        in.close();
    }

    private static int findLastWordLength(String str) {
        // 最后一个字符的位置
        int end = str.length() - 1;
        // 最后一个字母后面可能有空格
        while(end >= 0 && str.charAt(end) == ‘ ‘)
            end --;
        
        // 找最后一个字母之前的第一个空白字符
        int pos = end - 1;
        while(pos >= 0 && str.charAt(pos) != ‘ ‘)
            pos --;
        return end -pos;
    }
}

 

 




 

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

标签:

原文地址:http://www.cnblogs.com/zywu/p/5785382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!