Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] String에 substring, removeAt, insertAt 구현 본문

iOS 응용 (swift)

[iOS - swift] String에 substring, removeAt, insertAt 구현

jake-kim 2020. 12. 10. 00:29

기능

구현 내용

//
//  ViewController.swift
//  StringProcessing
//
//  Created by 김종권 on 2020/12/10.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("12345".substring(from: 1, to: 3))        // 234
        print("12345".remove(startInd: 2, length: 2))   // 125
        print("12345".insertAt(2, string: "7"))         // 127345
    }


}

extension String {
    // from부터 to까지 String
    func substring(from: Int?, to: Int?) -> String {
        if let start = from {
            guard start < self.count else {
                return ""
            }
        }

        if let end = to {
            guard end >= 0 else {
                return ""
            }
        }

        if let start = from, let end = to {
            guard end - start >= 0 else {
                return ""
            }
        }

        let startIndex: String.Index
        if let start = from, start >= 0 {
            startIndex = self.index(self.startIndex, offsetBy: start)
        } else {
            startIndex = self.startIndex
        }

        let endIndex: String.Index
        if let end = to, end >= 0, end < self.count {
            endIndex = self.index(self.startIndex, offsetBy: end + 1)
        } else {
            endIndex = self.endIndex
        }

        return String(self[startIndex ..< endIndex])
    }

    // startInd부터 length만큼의 문자열 삭제
    func remove(startInd: Int, length: Int) -> String {
        return self.substring(from: 0, to: startInd - 1) + self.substring(from: startInd + length, to: self.count - 1)
    }

    // positino인덱스에 string문자열 삽입
    func insertAt(_ position: Int, string: String) -> String {
        self.substring(from: 0, to: position - 1) + string + self.substring(from: position, to: self.count - 1)
    }
}

 

Comments