434. Number of Segments in a String

来源:互联网 发布:淘宝实体娃娃是真的吗 编辑:程序博客网 时间:2024/06/05 17:00

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
public class Solution {    public int countSegments(String s) {              if(s.length()==0||s.trim().isEmpty()) return 0;             String str=s.trim();         int j=0;         for(int i=0;i<str.length();i++){                        if(str.charAt(i)-'A'==-33&&str.charAt(i+1)-'A'!=-33)                j++;         }         if(j==0) return 1;         else return j+1;      }}
原创粉丝点击