基础知识三:字符串操作

1.定义

//字符串定义
var str1="hello " //字符串变量
let str2="hello " //字符串常量
let str3="" //空字符串
let str4=String() 

//字符定义
var char1:Character="m" //字符变量
let char2:Character="m" //字符常量

2.字符串是否为空

var tempStr = "abcd"
if !tempStr.isEmpty {
    print(tempStr)
}
//  abcd

3.字符串长度

 var str = "123456789"
 print(str.characters.count) //9

4.字符串遍历

//返回字符数组
var str = "hello"
for index in str.characters.indices{
    print(str[index])
}
//h
//e
//l
//l
//o

//返回字符串下标数组(使用 characters 属性的 indices 属性
                    会创建一个包含全部索引的范围(Range)
for index in greeting.characters.indices {
   print("\(greeting[index]) ", terminator: "")
}
// 打印输出 "G u t e n   T a g ! "

5.增

5.1 字符串增加

var str1 = "hello "
var str2 = "world"
print(str1 + str2) //hello world

5.2 增加字符

var tempStr = "hello"
var ch = "!"
var chs = "ab"
tempStr.append(ch)
tempStr.append(chs)
print(tempStr) //hello!ab

chs +=String(ch)
print(chs) //ab!

6.删

var welcome = "hello there!"
//删除某一个元素
welcome.remove(at: welcome.index(welcome.startIndex, offsetBy: 3))
print("\(welcome)") //helo
//删除字符串
let range = welcome.index(welcome.endIndex, offsetBy: -6)..

7.改

//插入字符
var welcome = "hello"
var worldStr = " world "
welcome.insert("!", at: welcome.endIndex)
print("\(welcome)") //hello!

//插入字符串
welcome.insert(contentsOf:worldStr.characters, at: welcome.index(welcome.startIndex, offsetBy: 3))
print("\(welcome)") //hel worldlo!

8.查

startIndex属性可以获取一个String的第一个Character的索引

endIndex属性可以获取最后一个Character的后一个位置的索引

greeting[greeting.endIndex] // error

greeting.index(after: endIndex) // error

let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a

9.是否包含子串contains

let str1="hello world"
let str2="world"
let range=str1.rangeOfString(str2)
if range != nil{
 //包含
}

10.字符串替换replace

//将 target 替换成 replacement
func replacingOccurrences(of target: String, with replacement: String) -> String

var k  = "hello"
var t = k.replacingOccurrences(of: "lo", with: "ab")
print(t) //helab

//将字符串范围的值替换掉
func replacingCharacters(in range: NSRange, with replacement: String) -> String

var k : NSString = "hello" //替换的时候需要显示申明NSString类型
var g = k.replacingCharacters(in: NSMakeRange(0, 1), with: "abc")
print(g)     //abclo

你可能感兴趣的:(基础知识三:字符串操作)