【Leetcode 434. Number of Segments in a String】

来源:互联网 发布:聊天机器人对话数据库 编辑:程序博客网 时间:2024/05/17 11:37

434. Number of Segments in a String

Total Accepted: 3749Total Submissions: 9646Difficulty: EasyContributors: love_FDU_llp

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: “Hello, my name is John”
Output: 5

java解决方法:

package Test;public class NumberSegments {    public static void main(String[] args) {        // TODO Auto-generated method stub        NumberSegments test=new NumberSegments();        test.countSegments(", , , ,        a, eaefa");    }    public int countSegments(String s) {        if("".equals(s)){            return 0;        }        int count=0;        String [] aStrings=s.split(" ");        for(int i=0;i<aStrings.length;i++){            if(!"".equals(aStrings[i])){                count++;            }        }        System.out.println(count);        return count;    }}
0 0
原创粉丝点击