Swift3 - String 字符串、Array 数组、Dictionary 字典的使用
Swift相关知识,本随笔为 字符串、数组、字典的简单使用。
///***********************************************************************************************************/
/// 2016.12.29
///***********************************************************************************************************/
1、Swift3 ,字符串的简单使用,直接将代码贴过来,更方便查看
// 字符串 stringfunc stringTest() -> Void {// 字符串let str1 = "yiyi"let str2 = "2222"var str3 = String()//空stringvar str4 = ""// 空string// 字符(字符为 一 个)let char1:Character = "d"// 字符串长度var strCount = str1.characters.countstrCount = str1.lengthOfBytes(using: String.Encoding.utf8)print(String(format:"strCount == "),strCount)// 字符串转换integerprint((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 = 10let int2 = 11.1let 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+ss2if ss1 == ss2 {print("ss1=ss2")}if ss1+ss2 == ss3 {print("ss1+ss2=ss3")}if ss1 > ss2 {// h大于bprint("ss1>ss2")}// 判断字符串是否包含字符串if (ss3 .range(of: ss1) != nil) {print("字符串包含子串")} if ss3.hasPrefix("he") {} if ss3.hasSuffix("a") {}
// 字符串 大小写print(ss3.uppercased())// HELLO,BANANAprint(ss3.capitalized)// Hello,Bananaprint(ss3.lowercased())// hello,banana/*// 这两个用法没 明白 print(ss3.uppercased(with: Locale(identifier: "l")))// HELLO,BANANAprint(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: ",")!]);// helloprint(ss3[ss3.index(ss3.startIndex, offsetBy: 4)])// o 取字符串的某个字符ss3.remove(at: ss3.characters.index(of: ",")!)// 去除字符串中特殊字符print(ss3)// hellobanana }
2、数组的简单使用
// 数组 arrayfunc arrayTest() -> Void {// 初始化 // var array1:[Any] = []// 空 任意类型 // var array2 = Array<Any>() // var array3:[String] = []// 空 string 类型 // var array4 = Array<String>() // let array5 = Array<Any>(repeatElement("", count: 3))var arr0 = ["what","test","swift","array"]let arr1 = ["hyArr",1,"hySwift",3] as [Any]var arr2 = [1,"2","swiftArr2",3,9,5] as [Any]print(arr2[0], arr2[3], separator: "* ")// arr0.count 数组countprint(String(format:"arr0 长度 == "),arr0.count)// 判断数组是否为空if arr1.isEmpty {print("arr1数组是空")}else {print("arr1数组不空")}// arr1[arr1.count-2] 取数组的某个元素print(arr1[arr1.count-2])// hySwift // print(arr1[0])// hyArr// public var first: Self.Iterator.Element? { get }print(arr1.first!)// hyArr// 遍历数组for i in 0..<arr1.count {print(arr1[i])}// 包含if arr0 .contains("test") {print("数组包含 test")}else {print("数组不包含 test")}// 删除元素 // arr2 .remove(at: 4) // arr2 .removeSubrange(1..<3)// 删除 1、2 两个元素 // arr2 .removeLast() // arr2 .removeFirst() arr2 .removeAll()print(arr2)// 添加元素arr2 .append("new1")// ["new1"]arr2.append(contentsOf: ["Shakia", "William"])print(arr2)arr2 = arr1 + arr2// ["hyArr", 1, "hySwift", 3, "new1"]arr2 = arr1arr2 .insert("insertElement", at: 3)//["hyArr", 1, "hySwift", "insertElement", 3, "new1"]// 更换if let i = arr0.index(of: "test") {arr0[i] = "测试"}arr2[0] = "domy"print(arr2)// 数组排序var sortArr = [3,5,1,0,8,0]sortArr.sort(by: >)print(String(format:"排序后:"),sortArr)// 排序后: [8, 5, 3, 1, 0, 0]// 二维数组let tArr1 = [["tSwift","haha"],1,[3,2]] as [Any]let subArr1 = tArr1[0]print(subArr1)/// Array => NSArray/// 苹果的例子/// Description:/// The following example shows how you can bridge an `Array` instance to/// `NSArray` to use the `write(to:atomically:)` method. In this example, the/// `colors` array can be bridged to `NSArray` because its `String` elements/// bridge to `NSString`. The compiler prevents bridging the `moreColors`/// array, on the other hand, because its `Element` type is/// `Optional<String>`, which does *not* bridge to a Foundation type.let colors = ["periwinkle", "rose", "moss"]let moreColors: [String?] = ["ochre", "pine"]let url = NSURL(fileURLWithPath: "names.plist")(colors as NSArray).write(to: url as URL, atomically: true)// true (moreColors as NSArray).write(to: url as URL, atomically: true)// error: cannot convert value of type '[String?]' to type 'NSArray'/// Array 的更多其他用法点进去查看方法文档}
3、字典的简单使用
// 字典 dictionaryfunc dictionaryTest() -> Void { // 创建字典var dict = [200:"ok",400:"error"]// [key:value]var emptyDict: [String: Any] = [:]// 空字典 var emptyDict: [Int: String] = [:]emptyDict = ["key1":"value1","key2":2]// Getting and Setting Dictionary Valuesprint(dict[200]!)// okprint(emptyDict["key1"]!)// value1// 添加键值对emptyDict["key3"] = "value3"print(emptyDict)// ["key2": 2, "key3": "value3", "key1": "value1"]// 更新键值对的valueemptyDict["key2"] = "updateValue2"print(String(format:("更换value后:")),emptyDict)var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 15],"triangular": [1, 3, 6, 10, 15, 21, 28],"hexagonal": [1, 6, 15, 28, 45, 66, 91]]// 排序for key in interestingNumbers.keys {interestingNumbers[key]?.sort(by: >)}print(interestingNumbers["primes"]!)/// print(interestingNumbers)/// ["hexagonal": [91, 66, 45, 28, 15, 6, 1],/// "primes": [15, 13, 11, 7, 5, 3, 2],/// "triangular": [28, 21, 15, 10, 6, 3, 1]]// 遍历字典let imagePaths = ["star": "/glyphs/star.png","portrait": "/images/content/portrait.jpg","spacer": "/images/shared/spacer.gif"]for (key, value) in imagePaths {print("The path to '\(key)' is '\(value)'.")}/// search a dictionary's contents for a particular value // let glyphIndex = imagePaths.index { // $0.value.hasPrefix("/glyphs") // } // print(imagePaths[glyphIndex!].value)// /glyphs/star.png // print(imagePaths[glyphIndex!].key)// starlet glyphIndex = imagePaths.contains {$0.value.hasPrefix("/glyphx")}print(glyphIndex)// ture/// Bridging Between Dictionary and NSDictionary// imagePaths as NSDictionaryprint("keys:\((imagePaths as NSDictionary).allKeys) ,values:\((imagePaths as NSDictionary).allValues)")}
转载于:https://www.cnblogs.com/zhangying-domy/p/6215779.html
Swift3 - String 字符串、Array 数组、Dictionary 字典的使用相关推荐
- List数组,string数组,Dictionary字典三种contain方法的查询速度
在生成随机不重复数时要判断生成的数是否已生成过,这时就要和原来生成的数进行比较是否有重复,有以下三种方法 1. list数组采用contains()方法 2.string数组采用contains()方 ...
- OC基础第四讲--字符串、数组、字典、集合的常用方法
OC基础第四讲--字符串.数组.字典.集合的常用方法 字符串.数组.字典.集合有可变和不可变之分.以字符串为例,不可变字符串本身值不能改变,必须要用相应类型来接收返回值:而可变字符串调用相应地方法后, ...
- iOS开发:沙盒机制以及利用沙盒存储字符串、数组、字典等数据
iOS开发:沙盒机制以及利用沙盒存储字符串.数组.字典等数据 1.初识沙盒:(1).存储在内存中的数据,程序关闭,内存释放,数据就会丢失,这种数据是临时的.要想数据永久保存,将数据保存成文件,存储到程 ...
- String字符串转数组空格处理
char数组和String互相转换 String str=" "; //创建一个字符串变量str char[] c; //创建一个字符数组c c = str.toCharArray ...
- Swift学习字符串、数组、字典
一.字符串的使用 let wiseWords = "\"I am a handsome\"-boy" var emptyString = "" ...
- 列表(list)、元组(tuple)、字典(dictionary)、array(数组)-numpy、DataFrame-pandas 、集合(set)...
一.列表(list) 一组有序项目的集合.可变的数据类型[可进行增删改查] 列表是以方括号"[]"包围的数据集合,不同成员以","分隔. 列表中可以包含任何数据 ...
- 【Python】数据类型 Number数字、String字符串、List列表、Tuple元组、Set集合、Dictionary字典
Python数据类型 2021/6/3 周四 学习内容: Python数据类型.Number(数字).String(字符串).List(列表).Tuple(元组).Set(集合).Dictionary ...
- php 字符串放到数组中,在PHP中将字符串转换为数组(Converting string into array in php)...
在PHP中将字符串转换为数组(Converting string into array in php) 我有像下面的字符串 ["Day1"]["Morning" ...
- 字符串String类型 、数组 Array类型
String类型的方法 方法 描述 charAt, charCodeAt, codePointAt 返回字符串指定位置的字符或者字符编码. indexOf, lastIndexOf 分别返回字符串中指 ...
最新文章
- oracle单表高并发,见过这么高并发( logons current)的数据库么?
- linux最常用的目录表示,Linux磁盘分区的命名方式和常用目录?【每日一个知识点第84期-Linux】...
- [ZJOI2009]假期的宿舍
- IDEA Maven创建多个Module相互依赖
- Redis学习之Docker环境搭建
- iphone储存空间系统怎么清理_教你快速清理 iPhone 系统缓存垃圾,拒绝卡顿!
- specular图使用方法_Unity| Specular高光反射初探(上)
- fastdfs安装部署
- 【学术杂谈】施一公:论文和科技实力是两回事,大家千万要分开
- java fx设置按钮背景_带透明背景的JavaFX按钮
- mysql --force 无效_【技能库】--mysql 索引失效 force index也失效-- 原因解决方案(256)...
- Preference Learning——Object Ranking
- oracle讲表通过主键去重,数据库试题,数据库基础试题及答案
- 应付模块的R12 TRACE 和 FND Debug 文件 / FND 日志 调试
- 使用data breakpoint 追踪地址寄存器被修改的问题
- PHP自适应小说网站源码深度SEO优化自动采集
- SATA与PCI-E速度对比
- 腾讯云轻量数据库服务简单测评
- vue 实现在线预览excel
- 要是我早点学会了使用三叉戟(Docker),那我不是就有时间像海王一样去找小姐姐们