1. 程式人生 > 其它 >Dart 資料型別 - String

Dart 資料型別 - String

宣告字串(String)  (1)、單行字串:單引號、雙引號都可以  (2)、多行字串:三個引號可以宣告包含字串的字串
 正則表示式  (1)、RegExp(r'正則表示式')  (2)、RegExp(r'\d+')
void main() {
  // 宣告字串
  var str1 = 'Hello world'; // 單引號
  var str2 = "Hello Dart"; // 雙引號

  String str3 = 'Hi World'; // 單引號
  String str4 = "Hi Dart"; // 雙引號

  print('$str1, $str2, $str3, $str4');

  // 通過三個引號宣告字串
  String str5 = '''字串
    拼接
  ''';
  print(str5);
  String str6 
= """---- Dart Flutter """; print(str6); /* 常見操作 */ // 字串是不可以修改的,常見的字串操作都會返回一個新的字串 // 1、字串拼接 print(str1 + str2); print('$str1 $str2'); // 獲取字串長度 print('str1 has ${str1.length} letters'); // str1 has 11 letters print(str1[0]); // H print('dart' == 'dart'); // true print('dart'.compareTo('dart')); //
0 // 2、字串的分割 print(str1.split(',')); // [Hello world] // 3、去除首尾空格 print(' a bc '.trim()); // a bc // 4、判斷字串是否為空 print(''.isEmpty); // true print(''.isNotEmpty); // false // 5、字串替換 print(str1.replaceAll('world', '世界')); // Hello 世界 // 支援正則替換 print('j1h2j3h4ppp'.replaceAll(RegExp(r'\d+'), '-')); //
j-h-j-h-ppp // 6、通過正則匹配手機號 var isPhone = RegExp(r'^1\d{10}$'); print(isPhone.hasMatch('13423459878')); // true print(isPhone.hasMatch('1234567892')); // false // 7、查詢字串 print(str1.contains('h')); // false print(str1.endsWith('d')); // true print(str1.startsWith('H')); // true // 8、定位字串 print(str1.indexOf('h')); // -1 print(str1.indexOf('H')); // 0 // 9、轉換大小寫 print('daRt'.toLowerCase()); // dart print('daRt'.toUpperCase()); // DART // 10、子字串,含頭不含尾 print('dart'.substring(0, 3)); // dar }