【swift總結】字串和字元

來源:互聯網
上載者:User

標籤:

聲明字串
var str = "Hello, playground"   //聲明一個字串var emptyStr = "";      //聲明一個空的字串var emptyStr1 = String();   //相等於上面的那個
str.isEmpty;    //判斷str是不是為空白falseemptyStr.isEmpty;   //true
字串串連
var str1 = "hello";var str2 = "world";var str = str1 + str2;
列印字串中的每個字元
for character in str.characters {    print(character);}
聲明字元
let c: Character = "a"; //‘a‘是錯誤的let cat:[Character] = ["c", "a", "t", "!"];     //聲明一個字元數組let catStr = String(cat);   //將字元數組變為字串
字串後面追加字元
let c: Character = "a";catStr.append(c);
字串插值

可以使用”(value)”方式往字串中插入值,構建一個新的字串

let someNum: Int = 40;let message = "我有\(someNum)包茶葉";
字串含有字元的數量
let num = message.characters.count  //message字串含有的字元
訪問和修改字串使用下標訪問
let greet = "good morning";/*startIndex代表字串開始的下標*/greet[greet.startIndex];/*endIndex代表字串結束的下面    predecessor代表前一個*/greet[greet.endIndex.predecessor()];/*successor錶帶繼續的也就是下一個*/greet[greet.startIndex.successor()];/*字串不支援直接存取下標,需要使用advance函數轉化,如果訪問的下標超出字串就會發出執行階段錯誤*/let index = advance(greet.startIndex, 7);greet[index];greet[7]    //語法錯誤greet[greet.endIndex];  //錯誤greet[greet.endIndex.successor()];  //錯誤
使用indices建立一個下標範圍
for index in indices(greet) {    print("\(greet[index])");}
往字串中添加和刪除元素

var greet = "hello";/*使用insert插入字元*/greet.insert("!", atIndex: greet.startIndex);/*使用splice插入字元組*/greet.splice("world".characters, atIndex: greet.endIndex);/*removeAtIndex移除在某個下標的字元*/greet.removeAtIndex(greet.startIndex);/*建立一個範圍,然後移除這個範圍*/let range = advance(greet.startIndex, 5)..<greet.endIndex;greet.removeRange(range);
字串比較
let str1 = "hello";let str2 = "hello"str1 == str2;   //比較兩個字串是否相等
let strs = ["hello", "morning", "happy"];for str in strs {//判斷字串開頭是否包含he    if(str.hasPrefix("he")) {        print(str);//判斷字串結尾是否包含ng    }else if str.hasSuffix("ng") {        print(str);    }}

【swift總結】字串和字元

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.