zoukankan      html  css  js  c++  java
  • 《从零开始学Swift》学习笔记(Day 14)——字符串的插入、删除和替换

    原创文章,欢迎转载。转载请注明:关东升的博客

          对应可变字符串可以插入、删除和替换,String提供了几个方法可以帮助实现这些操作。这些方法如下:

    splice(_:atIndex:)。在索引位置插入字符串。

    insert(_:atIndex:)。在索引位置插入字符。

    removeAtIndex(_:)。在索引位置删除字符。

    removeRange(_:)。删除指定范围内的字符串。

    replaceRange(_:, with: String) 。使用字符串或字符替换指定范围内的字符串。

    代码:

    var str = "Swift"

    print("原始字符串:(str)")

     

    str.splice("Objective-C and ".characters, atIndex: str.startIndex)

    print("插入字符串后:(str)")

     

    str.insert(".", atIndex: str.endIndex)    

    print("插入.字符后:(str)")

     

    str.removeAtIndex(str.endIndex.predecessor())

    print("删除.字符后:(str)")

     

    var startIndex = str.startIndex           

    var endIndex = advance(startIndex, 9)     

    var range = startIndex...endIndex     

     

    str.removeRange(range)                

    print("删除范围后:(str)")

     

    startIndex = str.startIndex

    endIndex = advance(startIndex, 0)

    range = startIndex...endIndex      

     

    str.replaceRange(range, with: "C++")  

    print("替换范围后:(str)")

    输出结果:

    原始字符串:Swift

    插入字符串后:Objective-C and Swift

    插入.字符后:Objective-C and Swift.

    删除.字符后:Objective-C and Swift

    删除范围后:C and Swift

    替换范围后:C++ and Swift

    欢迎关注关东升新浪微博@tony_关东升。

    关注智捷课堂微信公共平台,了解最新技术文章、图书、教程信息

                           

    更多精品iOS、Cocos、移动设计课程请关注智捷课堂官方网站:http://www.zhijieketang.com

    智捷课堂论坛网站:http://51work6.com/forum.php

  • 相关阅读:
    实习项目1.
    try catch finally的用法
    asp.net 验证控件
    数据库操作语言
    webform Response的一些成员
    jQuery
    C#@的用法
    SQL分页查询
    抽象类与接口的区别
    抽象类与接口
  • 原文地址:https://www.cnblogs.com/iOS-Blog/p/4818413.html
Copyright © 2011-2022 走看看