3.字符串類型的應用

類型 描述語句
字串 String
#### 使用方式
var name = "Ahwu";
var str3 = "Hello ${name} $name";
var num1 = 3;
var num2 = 4;
var str4 = "3+4=${num1+num2}";
var str1 = "Hello";
var str2 = "World";
print(str1+str2);//HelloWorld
print('hello''world');//helloworld
var str5 = '''第一行
第二行
第三行''';
var str6 = """第一行
第二行
第三行
"""
print('hello \'Ahwu\'');//hello 'Ahwu'
print("hello\nworld");
//hello
//world
print(r"hello\nworld");//hello\nworld
//如果你不想進行轉譯,想讓字符串完全匹配其字面的意思,就可以使用原始字符串
//其實也可以使用構造方法來創建字符串,例如:
var str7 = String.fromCharCode(97);//字符碼97對應字符a
var str8 = String.fromCharCodes([97,98,99]);//abc
//獲取字符串的字符碼集合
print(str8.codeUnits);//[97, 98, 99]
//獲取當前字符串是否為空字符串,返回布爾值
print("".isEmpty) ; / /true
//獲取當前字符串是否為非空,返回布爾值
print("".isNotEmpty) ;//false
//獲取當前字符串長度
print(str8.length);//3
//獲取類型
print(str8.runtimeType);//String
//通過下標獲取某個字符中中某個字符的code碼,下標從0開始
print("hello".codeUnitAt(0));//104
//進行字符中比較,遂個字符進行code 碼的比較
print("hello".compareTo('a'));//1
//獲取當前字符中是否包含參數字符電
print("hello".contains('1'));// true
//判斷當前字符串是否以某個字符申結尾
print("hello",endsWith("llo")) ;//true
//判斷當前字符中是否以某個字符中開頭
print("hello".startsWith('h'));//true
//獲取要進行匹配的字符串在當前字符中中的位置,如果沒找到,就返回一1
print("hello".indexOf("l"));//2
//獲取要進行匹配的字符串在當前字符電中的位置,逆向查找,如果沒找到,就返回1
print("hello".lastIndexof("l"));//3
//在左邊進行字符中位數補齊
print("hello".padLeft (10, "*"));//*****hello
//在右邊進行字符中位數補齊
print("hello".padRight(10, "&"));//hel1o&&&8&
//進行字符中換,將匹配到的字符中換成指定的字符中
print.("hello".replaceAll("o", "p"));//hellp
//將指定範圍內的字符中進行替換,左閉右開區間
print("hello".replaceRange (0, 3, "000"));//000lo
//使用指定字符中作為標記對原字符中進行分割,結果會放進列表返回
print("hello".split('e'));// [h, llo]
//進行學符電截取,左閉右開區間
print("hello".substring(1,3));//el
//將字符串全部轉為小寫
print("Hello" ,toLowerCase());//hello
//將字符中全部轉為大寫
print("hello" . toUpperCase());//HELLO
//將字符串首尾的空格去掉
print("   hello  ".trim)));
//將字符中首部的空格去掉
print("  hello".trimleft());
//將字符串尾部的空格去掉
print("hel1o  ".trimRight()) ;
### 拷貝字串
print("hello"*2)//hellohello
print("hello"[0])//h

Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments