swift字符串_04_字符串基本使用

//: Playground - noun: a place where people can play

import UIKit

//1.创建空字符串
var emptyStr1 = ""
var emptyStr2 = String() //使用构造函数来创建空串

//判断字符串是否为空串
let isEmpty = emptyStr1.isEmpty

//2.字符串的拼接
var name = "Kathy"
let height = String("160")

//(1)使用插值符号进行拼接
let fullString = "\(name)'s height is \(height)cm"

//(2)运算符+重载
let fullString2 = name + "'s height is " + height + "cm"

//(3)调用函数
name.appendContentsOf(fullString)

//3.字符串的比较
let str1 = "We are 伐木累"
let str2 = "We are 伐木累"

//相等
if str1 == str2 {
    print("str == str2")
}

//是否包含前后缀
str1.hasPrefix("We are")
str2.hasSuffix("kkk")

//4.获取字符串中的字符
var loopStr = "I am a single 🐶"
for char in loopStr.characters {
    
    print(char)
}

//5.获取字符串的长度
loopStr.characters.count

//6.根据下标获取到某个字符
loopStr[loopStr.startIndex] //第一个字符
loopStr[loopStr.endIndex.predecessor()] //loopStr.endIndex:末尾的下一个的序号

loopStr[loopStr.endIndex.advancedBy(-5)]

//7.插入删除
loopStr.insert("🌂", atIndex: loopStr.endIndex)
loopStr.removeAtIndex(loopStr.endIndex.advancedBy(-4))
print(loopStr)

 

posted on 2016-06-04 10:25  爱你久久iOS  阅读(197)  评论(0编辑  收藏  举报

导航