434. Number of Segments in a String

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

計算字符串中的段數,其中段被定義爲非空格字符的連續序列。

請注意,字符串不包含任何不可打印的字符。

例:

輸入:Hello, my name is John輸出: 5

思路:

用split方法分割字符串,接着循環判斷字符串數組元素是否爲空。注意判斷時控制不能用 “” 或者null來判斷,要用isEmpty()方法。

public int countSegments(String s) {
        String[] sa = s.split(" ");
        int result = 0;
        for(int i=0 ; i<sa.length ; i++){
            if( !sa[i].isEmpty() ) {
                result++;
                
            }
        }
        return result;
    }


發佈了38 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章