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

Posted 爱你久久

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)

 

以上是关于swift字符串_04_字符串基本使用的主要内容,如果未能解决你的问题,请参考以下文章

Swift 追加到数组给了我 EXC_BAD_INSTRUCTION EXC_l386_INVOP 在 32 位系统上

04_python基本的输入输出函数

Swift_1_基本数据类型

Swift 备忘清单_开发速查表分享

Linux04_基本命令

swift_通知的使用