跳到主要內容

發表文章

目前顯示的是 1月, 2024的文章

【Java語言】StringUtils 檢查字串是否空

此系列文章主要會記錄我在工作上遇到的程式語法。 工作上很常讀取字串,如網頁輸入後欄位內容、讀取DB內容等是不是有空值,就有用到這個方法,來判斷字串內容。 較常見的語法就是: StringUtils.isBlank(): 用來判斷字串是否為空,字串內容包含為空(null)、空字串符號、空格,皆會回傳true。 StringUtils.isNotBlank():此方法就是相反,檢查字串是否為null、是否為空字串、是否只有空格符號。 String str = “”; boolean isBlank = StringUtils.isBlank(str); System.out.println(isBlank) 工作上的寫法會是直接在條件上判斷: if (StringUtils.isBlank(str)) { //做相對應的處理 } StringUtils是 Apache Commons Lang函式庫,主要是處理「字串」類。 這邊列出常見的方法: 字串是否為空 isBlank() isEmpty() isNumberic() isAlphabetic() 字串轉換 upperCase() lowerCase() capitalize() replace() substring() 字串格式化 join() format() trim() split() [Java語法範例] // 判斷字串是否為空  // true boolean isBlank = StringUtils.isBlank(""); // 將字串轉換為大寫  // HELLO String upperCase = StringUtils.upperCase("hello"); // 將字串中的某個字串替換為另一個字串 // goodbye world String replaced = StringUtils.replace("hello world", "hello", "goodbye"); // 截取字串的子字串 // world String substring = StringUtils.substring("hello world", 5); // 將字串陣列合併為一個字