Swift相关知识,有时间就敲点,供自己学习总结,亦或也有幸能帮到他人,有理解、使用错误的地方也望能得到指正。
///***********************************************************************************************************/
/// 2016.12.23
///***********************************************************************************************************/
Swift3 ,字符串的简单使用,直接将代码贴过来,更方便查看
// 字符串 string func stringTest() -> Void { // 字符串定义 let str1 = "yiyi" let str2 = "2222" var str3 = String()//空string var str4 = ""// 空string // 字符定义(字符为 一 个) let char1:Character = "d" // 字符串长度 var strCount = str1.characters.count strCount = str1.lengthOfBytes(using: String.Encoding.utf8) print(String(format:"strCount == "),strCount) // 字符串转换integer print((str2 as NSString).integerValue) // 字符串拼接 str3 = str1 + str2 // str3 = "\(str1)\(str2)" // str3 = globalStr + String(str1) print(String(format:"str3 == "),str3) // 字符串与字符拼接 // str4 = str1+String(char1) str4 = "\(str1)\(char1)" str4 = str1.appending(String(char1))// 其他类型转换string String() exp:String(strCount) print(String(format:""),str4) //字符串与其他类型值的拼接 let int1 = 10 let int2 = 11.1 let str5 = String(format:"%i%.1f",int1,int2) print(String(format:"str5 == "),str5) // 字符串枚举 遍历每个字符 let s1 = "hello world!" if strCount != 0 { print("判断string长度不为0,不是空") } for c in s1.characters { print(c) } // 字符串比较 let ss1 = "hello" let ss2 = ",banana" var ss3 = ss1+ss2 if ss1 == ss2 { print("ss1=ss2") } if ss1+ss2 == ss3 { print("ss1+ss2=ss3") } if ss1 > ss2 {// h大于b print("ss1>ss2") } // 判断字符串是否包含字符串 if (ss3 .range(of: ss1) != nil) { print("字符串包含子串") } // 字符串 大小写 print(ss3.uppercased())// HELLO,BANANA print(ss3.capitalized)// Hello,Banana print(ss3.lowercased())// hello,banana /* // 这两个用法没 明白 print(ss3.uppercased(with: Locale(identifier: "l")))// HELLO,BANANA print(ss3.lowercased(with: Locale(identifier: "o")))// hello,banana */ // 截取 修剪 字符串 print(ss3.substring(from: ss3.characters.index(of: ",")!))//,banana 截取字符串从“,”开始 print(ss3.substring(to: ss3.characters.index(of: ",")!))//hello 截取字符串到“,”结束 print(ss3.unicodeScalars[ss3.unicodeScalars.startIndex ..< ss3.unicodeScalars.index(of: ",")!]);// hello print(ss3[ss3.index(ss3.startIndex, offsetBy: 4)])// o 取字符串的某个字符 ss3.remove(at: ss3.characters.index(of: ",")!)// 去除字符串中特殊字符 print(ss3)// hellobanana }
时间: 2024-10-23 16:43:47