1. 程式人生 > 其它 >SFDC String.isEmpty vs. String.isBlank

SFDC String.isEmpty vs. String.isBlank

SFDC String.isEmpty vs. String.isBlank

目錄

前言

專案接近尾聲了,開始編寫測試Class了。開始做測試類了之後發現了很多前期設計的問題,程式碼裡考慮的不全面一下子全都顯現出來了。
老生常談的空NULL0(數字為零),''(空字串),' '(只有空格)。
在字串判斷時候,發現String提供了兩個類似的方法:
String.isEmpty(String str)
String.isBlank(String str)
這兩個方法都返回一個Boolean

測試

Talk is cheap。show me the code!
寫了點測試的程式碼,測測這倆方法有啥不同。

String strBlank = '';
String strNull = null;
String strSpace = ' ';

System.debug('isEmpty(strBlank):'+String.isEmpty(strBlank));
System.debug('isEmpty(strNull):'+String.isEmpty(strNull));
System.debug('isEmpty(strSpace):'+String.isEmpty(strSpace));
System.debug('============================================');
System.debug('isBlank(strBlank):'+String.isBlank(strBlank));
System.debug('isBlank(strNull):'+String.isBlank(strNull));
System.debug('isBlank(strSpace):'+String.isBlank(strSpace));

結果如圖:

結論

可以通過Log得出結論

  1. 兩個方法都對字串為:NULL''(空字串)都能Check出來
  2. String.isEmpty(strSpace) :會認為空格也是字元
  3. String.isBlank(String str):則更加嚴格一點,空格不被認為有效字元