Swift-String的基本使用

版权声明: https://blog.csdn.net/qq_35122556/article/details/80184046

1.创建字符串

1.1最基本的使用(Swift会通过后面的赋值推断类型为String) 

let someString = "Some string leteral value"

let 声明的话,以后字符串someString 不能再被改变. 如果用Var 的话就可以改变.根据需求使用. 尽量用let,代码更强壮,优化更好一点

1.2多行字符串的创建(使用三个双引号引用起来"""    """   )

 let quotation = """
this is a big man
and wo are "haahh" ready
"""

1.3 多行字符串里,有双引号的时候需要用(\)来引用

 let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""

1.4 多行字符串开始或者结束带有空行的做法:

  """
 
This string starts with a line feed.
It also ends with a line feed.
 

1.5 初始化一个空的字符串:

  var emptyString = ""
  var anotherEmptyString = String()

2.字符串判空:

 if emptyString.isEmpty {
            print("Nothing to see here")
        }

3. 字符串的可变性:

var(声明出来的是变量)  let 声明出来的是常量

注意:这和oc有所不同oc里是通过选择NSString和NSMutableString来决定

以下是官方翻译:

字符串是值类型

        //Swift 的 String类型是一种值类型。如果你创建了一个新的 String值, String值在传递给方法或者函数的时候会被复制过去,还有赋值给常量或者变量的时候也是一样。每一次赋值和传递,现存的 String值都会被复制一次,传递走的是拷贝而不是原本。值类型在结构体和枚举是值类型一章当中有详细描述。

        

        //Swift 的默认拷贝 String行为保证了当一个方法或者函数传给你一个 String值,你就绝对拥有了这个 String值,无需关心它从哪里来。你可以确定你传走的这个字符串除了你自己就不会有别人改变它。

        

        //另一方面,Swift 编译器优化了字符串使用的资源,实际上拷贝只会在确实需要的时候才进行。这意味着当你把字符串当做值类型来操作的时候总是能够有用很棒的性能。

3.1 通过+把两个字符串拼接起来:

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"

或者 +=

var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

或者通过append()在字符串末尾加一个值

welcome.append("!")

3.2 通过下标获取某个位置的字符串:

3.2.1 获得第一个和最后一个字符:

let geeting = "Guten Tag!"
let firstStr = geeting[geeting.startIndex] //G
let endStr = geeting[geeting.index(before: geeting.endIndex)] //!

3.2.2获得第一个字符后面的字符

let str1 = geeting[geeting.index(after: geeting.startIndex)] //u

当然访问索引范围之外的字符串那是会崩溃滴

3.2.3 获取从开始(0)算起的索引号是7的字符串

let index = geeting.index(geeting.startIndex,offsetBy:7)//o

3.2.4 遍历字符串

for index in geeting.characters.indices
        {
            print("\(geeting[index]) ", terminator: "")
        }

3.2.5 插入和删除

你可以在任何遵循了Idexable 协议的类型中使用startIndex 属性以及,index(before:), index(after:)和index(_:offsetby)方法.

包括这里使用的 String ,还有集合类型比如 Array , Dictionary 和 Set 

var welcome3 = "hello"
welcome3.insert("!", at: welcome3.endIndex)     //hello!

welcome3.insert(contentsOf: " there", at: welcome3.index(before: welcome3.endIndex)) //hello there!

welcome3.remove(at: welcome3.index(before: welcome3.endIndex)) //hello there!

let range = welcome3.index(welcome3.endIndex, offsetBy: -6)..<welcome3.endIndex
welcome3.removeSubrange(range)//hellohello!

welcome3.insert(contentsOf: " there", at: welcome3.index(before: welcome3.endIndex)) //hello there!

welcome3.remove(at: welcome3.index(before: welcome3.endIndex)) //hello there!

let range = welcome3.index(welcome3.endIndex, offsetBy: -6)..<welcome3.endIndex
welcome3.removeSubrange(range)//hello

3.2.6 截取某个字符串的特定符号之间的字符串

/字符串范围截取  
let num = "123.45"  
let deRange = num.range(of: ".")  
  
//FIXME:按某个字符串截取  
  
//截取小数点前字符(不包含小数点)  123  
let wholeNumber = num.prefix(upTo: deRange!.lowerBound)  
//截取小数点后字符(不包含小数点) 45  
let backNumber = num.suffix(from: deRange!.upperBound)  
//截取小数点前字符(包含小数点) 123.  
let wholeNumbers = num.prefix(upTo: deRange!.upperBound)  
//截取小数点后字符(包含小数点) .45  
let backNumbers = num.suffix(from: deRange!.lowerBound)  

3.2.7 字符串和字符相等使用“等于”运算符 ( ==) 和“不等”运算符 ( !=)进行检查:

let quotation428 = "We're a lot alike, you and I."
let sameQuotatio = "We're a lot alike, you and I."
if quotation428 == sameQuotatio {
        print("These two string are considered equal")
     }

前缀,后缀相等用 hasPrefix 和 hasSuffix 

if scene.hasPrefix("Act 1"){}
if scene.hasSuffix("Capulet's mansion"){}

3.2.8字符串常用的截取n到n+m位置的字符串

var str = "abcdeflovewhrdsdada"
        let index1 = str.index(str.startIndex, offsetBy: 6)
        let index2 = str.index(str.startIndex, offsetBy: 13)
        let result = str[index1 ..< index2] //lovewhr

3.2.9 截取两个特定字符之间的字符串

var str = "abcdef&lovewhr*dsdada"
        let index1 = str.index(after: str.index(of: "&")!)
        let index2 = str.index(of: "*")
        let result = str[index1 ..< index2!]
        print(result) //lovewhr


先写这么多吧,后续再补充.吃饭去....

猜你喜欢

转载自blog.csdn.net/qq_35122556/article/details/80184046