Swift字符串类型

字符串初始化

 1、初始化

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. let  someString        =   "Some      string    literalvalue"  
  2.    
  3.    
  4.    
  5. let wiseWords = "\"Imagination is moreimportant than knowledge\" -Einstein" let  dollarSign      =   "\x24"                  //  $,  
  6. Unicodescalar U+0024  
  7.    
  8. let  blackHeart       =   "\u2665"               //  ♥,  
  9. Unicodescalar U+2665  
  10.    
  11. let  sparklingHeart        =  "\U0001F496"           //  
  12.    
  13. , Unicode scalarU+1F496  

2、空值

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. var emptyString = ""                                //  
  2. 空串初始化  
  3. var anotherEmptyString = String()              //  通 过初始化函数初始化  
  4.    

3、空值判断

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. if emptyString.isEmpty{  
  2.    
  3. println("Nothing to see here")  
  4.    
  5. }  

字符串修改

var 声明的可以修改,let 不能修改。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. var variableString = "Horse" variableString+= " and carriage"  
  2.    
  3.    
  4.    
  5.    
  6. let constantString = "Highlander" constantString  += "  and   another  
  7.   
  8. Highlander" //错误  
  9.    

 

 

字符串插入

 

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. let multiplier = 3  
  2.    
  3. let message = "\(multiplier) times 2.5 is  
  4. \(Double(multiplier) * 2.5)"  

 

 

字符串长度

 

使用 countElements函数。

 

 

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. let  unusualMenagerie            =  "Koala     , Snail, Penguin,Dromedary" println("unusualMenagerie                     has  
  2. \(countElements(unusualMenagerie))  
  3. characters")  

 

比较字符串相等

 

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. let quotation = "We're a lot alike, you and I."let sameQuotation = "We're a lot alike, youand I."  
  2.    
  3.    
  4. if quotation == sameQuotation {  
  5.    
  6. println("These         two       strings      areconsidered equal")  
  7.    
  8. }  

 Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485

猜你喜欢

转载自guandongsheng.iteye.com/blog/2080666