Swift字符串基本操作(二)

4字符串的字符大小写转换

字符串的uppercased()方法可以把字符串所有的小写字符变成大写字符

字符串的lowercased()方法可以把字符串所有的大写字符变成小写字符

字符串的capitalized方法可以把字符串首字符大写

示例:

1 |  var str = "hello world"

2 |  str = str.uppercased()

3 |  print("转换为大写:\(str)")

4 |  str = str.lowercased()

5 |  print("转换为小写:\(str)")

6 |  str = str.capitalized

7 |  print("首字母大写:\(str)")

运行结果:

转换为大写:HELLO WORLD

转换为小写:hello world

首字母大写:Hello World

5字符串插入

示例:

1 |  let number = 9

2 |  let total = "\(number)*2 = \((number)*2)"

3 |  print(total)

输出为:9*2 = 18

以将常量number插入字符串中为例,需要插入时需要用\(number)形式插入到字符串中,会被自动替换下来,如果需要进行运算需要加上括号直接运算 但是计算结果依然需要\()形式输出

我们还可以通过str.insert(newElement: Character, at:Index)来对字符串插入新的字符,字符串的起始下标为str.startIndex,结束下标为str.endIndex,打印字符串的第一位字符时候利用str[str.startIndex]方法访问。

1 |  var str = "hello swift"

2 |  str.insert("w", at: str.index(after: str.startIndex))

3 |  print("insert:\(str)")

输出结果:insert:hwello swift

5.2.6字符串添加

如果是在字符串后边添加一个字符我们使用str.append()方法实现。如果在字符串后添加一个字符串我们使用字符串拼接“+”或者使用str.append(String)方法,示例代码如下:

1 |  var str = "hello"

2 |  let apdc:Character = "o"

3 |  str.append(apdc)

4 |  print("添加字符:\(str)")

5 |  str+="world"

6 |  print("添加字符串:\(str)")

运行结果:

添加字符:helloo

添加字符串:hellooworld

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • //: Playground - noun: a place where people can play impo...
    艾希_可可阅读 346评论 0 0
  • 申请地址:https://developer.apple.com/enroll/duns-lookup/ 注:通过...
    LiuTianXiang阅读 68,705评论 17 54
  • 主场外交的意义:争取话语权、定价权(产品、技术、定价)。一带一路的意义:动机、条件、挑战、战略意义。通信成本显示了...
    一树花海阅读 791评论 0 0
  • Rust标准库创建线程的函数有如下签名: 可以看到,spawn函数对泛型参数F和T都有Send + ’static...
    swapmem阅读 3,720评论 0 1
  • 夏日里漫长的白昼过去,黑夜到来。河面上只有一只小船,船上也只有一个人,看不清脸孔,不知道他的年纪,也没见他怎么动作...
    叶有念阅读 173评论 0 0