let string = "string literal value"
常量string将会自动推断为String类型
var emptyStr = "" //使用空字符串字面量var anotherEmptyStr = String() //使用构造方法//两者没有区别
使用isEmpty判断空String:
if emptyStr.isEmpty { print("have nothing here")}
使用“+”连接字符串,当然也支持自加运算符”+=”
var variableStr = "Lastname"variableStr += "and Firstname"/// variableStr is "Lastname and Firstname"//**but if:let constantStr = "Gender"constantStr += "and another Highlander"///编译器会报错,被声明为常量的字符串不能被修改!
跟oc不同,swift的String通过var/let 变量/常量 标识决定其是否可变(can be mutated),而不需要选择Nsstring 还是 NSMutableString。
区别引用类型,在String在方法间传递,或者将其赋值给一个常量或者变量时,该String将会被复制(copy),而不是指向原来的对象。
let str = "hello world "let char: Character = "!"str.append(char)// 结果str为: "hello world !"
for char in "myStr".characters { print(char)} //m //y //S //t //r
在字符串中插入常量变量表达式等,构造一个新的字符串”通过()”:
let multiplIEr = 3let message = "\(multiplIEr) times 2.5 is \(Double(multiplIEr) * 2.5)" /// message is "3 times 2.5 is 7.5"
在字符串中输入反斜线”\” 水平制表符”t” 换行”n” 双引号”“” 单引号”’” 等都需要在前面添加”\”进行转义,同时可以在转义字符后添加Unicode来进行特殊符号表情的显示:
//**双引号let wiseWords = "\"Imagination is more important than kNowledge\" - Einstein"///"Imagination is more important than kNowledge" - Einstein//**Unicodelet dollarsign = "\u{24}" // $,Unicode scalar U+0024let blackHeart = "\u{2665}" // ♥,Unicode scalar U+2665let sparklingHeart = "\u{1F496}" // ��,Unicode scalar U+1F496//**扩展自行集//**对应关系// \u{D55C}----한// \u{1112}----ᄒ// \u{1161}----ᅡ// \u{11AB}----ᆫlet KoreaStr = "\u{D55C}\u{1112}\u{1161}\u{11AB}" //한한
string.characters.count
let str = "1234567890"print("str has \(str.characters.count) characters")//输出 "star has 10 characters"//**为String增加笔画不会造成长度增加:var str = "cafe"print("the number of characters in \(word) is \(word.characters.count)")// 输出 "the number of characters in cafe is 4"//**Now append some Unicode:word += "\u{301}"print("the number of characters in \(word) is \(word.characters.count)")//输出 "the number of characters in café is 4"//仅仅是改变了最后一个字符,并没有增加字符串的长度
正因为swift支持扩展字形集,不同的字符,和相同的不同表示的字符可能需要不同量的存储器来存储,所以在swift中characters所占用的存储量是不一定相同的,因此不能像oc计算Nsstring那样使用字符串来迭代计算,而应该遍历字符串的characters来确定字符串的长度。
可以通过其方法和属性,或者下标,来访问或者修改字符串
swift中的字符串具有相关连的索引类型(String.Index),可对应其每个位置的Character
正如上面所说,不同的字符串可能需要不同数量的内存来存储,所以为了确定哪些character在特定的位置上,我们必须遍历确定每个Unicode的开始结束位置,因此,String不能使用整形作索引。
startIndex: 访问String第一个位置的字符
endindex: 访问String最后一个位置的字符
(一个空的字符串或者长度为1的字符串,startIndex和endindex相等)
predecessor(),successor(),advancedBy()
一个String.Index值可以通过调用predecessor()方法来访问其前一个index,调用successor()来访问其后一个index,或者调用advancedBy()来指定访问相对位置的index( 之后5位的index: advancedBy(5) 往前5位的index: advancedBy(-5) )
let greeting = "Guten Tag!"greeting[greeting.startIndex]//Ggreeting[greeting.endindex.predecessor()]//!greeting[greeting.startIndex.successor()]//ulet index = greeting.startIndex.advancedBy(7)//agreeting[index]//输出 a
indiced : 字符串Index的集合
for index in greeting.characters.indices { print("\(greeting[index])",terminator: " ")}///prints "G u t e n T a g !"
利用index,在制定位置插入字符character
var helloStr = "hello"helloStr.insert("~",atIndex: helloStr.endindex)// hello~
同理,插入字符串(字符的集合)
var helloStr = "hello!"helloStr.insertContentOf(" world!".characters,at: hello.endindex) // hello! world //用上面的知识,再追求下完美:var helloStr = "hello!"helloStr.insertContentOf(" world".characters,at: hello.endindex.predecessor()) // Hello World!
移除(index):
var helloStr = "Hello World!"helloStr.removeAtIndex(helloStr.endindex.predecessor())// hello world// 注意:endindex是指最后一个index位(将要输入内容的index位),所以删除最后一个字符使用的index是endindex.predecessor()(将要输入内容的index的前一个index位),而不是endindex
移除(Range):
var helloStr = "Hello World!"let range = Range(start: helloStr.endindex.advancedBy(-6),end: helloStr.endindex.predecessor())// 顺便贴一个new Range的简易写法:// let range = helloStr.endindex.advancedBy(-6)..<helloStr.endindex// 效果是一样的helloStr.removeRange(range)// hello
两个纯字符串比较
let onestr = "We're a lot alike,you and I."let anotherStr = "We're a lot alike,you and I."if onestr == anotherStr { print("These two strings are consIDered equal")}//输出: These two strings are consIDered equal//相等
两个由characters组成的字符串比较
let onestr = "Voulez-vous un caf\u{E9}?"//Voulez-vous un café?let anotherStr = "Voulez-vous un caf\u{65}\u{301}?"//Voulez-vous un café?//两者虽然看起来内容字符不同,其实\u{65}\u{301}是一个e和一个音调符号,根据上面的知识,结果组合成é(\u{E9})if onestr == anotherStr { print("These two strings are consIDered equal")}//输出: These two strings are consIDered equal//相等
两个表现相同的character比较
let oneChar: Character = "\u{41}" //拉丁字母中的Alet anotherChar: Character = "\u{0410}" //西里尔字母中的Aif oneChar != anotherChar { print(These two characters are not equivalent)} //输出: These two characters are not equivalent //不相等!
前缀和后缀的比较
我们可以使用hasPrefix()方法和hasSuffix()去匹配String的前缀和后缀,并返回一个Boolean值
let romeoAndJulIEt = [ "Act 1 Scene 1: Verona,A public place","Act 1 Scene 2: Capulet's mansion","Act 1 Scene 3: A room in Capulet's mansion","Act 1 Scene 4: A street outsIDe Capulet's mansion","Act 1 Scene 5: The Great Hall in Capulet's mansion","Act 2 Scene 1: OutsIDe Capulet's mansion","Act 2 Scene 2: Capulet's orchard","Act 2 Scene 3: OutsIDe Friar LaWrence's cell","Act 2 Scene 4: A street in Verona","Act 2 Scene 5: Capulet's mansion","Act 2 Scene 6: Friar LaWrence's cell"]//----遍历这个字符数组,匹配下前缀看看效果var count = 0for str in romeoAndJulIEt { if str.hasPrefix("Act 1 ") { count++ }}print("There are \(count) string with Act 1 ")// 输出: "There are 5 string with Act 1"//----后缀呢var count = 0for str in romeoAndJulIEt { if str.hasSuffix("Capulet's mansion") { count++ } }print("There are \(count) mansion string")// 输出: "There are 6 mansion strsing"
复习一下,上面也提到,Swift中的String支持emoji表情和众多特殊字符,这也是String一个单位长度不一定等于两个character(汉字)或者1个character(英文字母)的原因。
先回到我们的话题。String和UTF-8的对应关系,我们来看一张官方电子书中的表:
//上图中对应的String://let dogString = "Dog!!��"//同时String中的UTF-8编码也是可以像char那样遍历的for unitCode in dogString.utf8 { print("\(unitCode) ",terminator: "")}//输出: 68 111 103 226 128 188 240 159 144 182
同理String也可以以UTF-16 和Unicode的方式遍历
for unitCode in dogString.utf16 {}for scalar in dogString.unicodeScalars { print("\(scalar.value) ",terminator: "")}// 68 111 103 8252 128054for scalar in dogString.unicodeScalars { print("\(scalar) ",terminator: "")}// D o g !! ��//注意: 直接printunicodeScalar的话跟String的输出是一样效果的,我们print出他的value,才是我们想要的编码总结
以上是内存溢出为你收集整理的swift中String和Character的使用与总结全部内容,希望文章能够帮你解决swift中String和Character的使用与总结所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)