Get the last character of a string without using array?

后端 未结 6 1915
甜味超标
甜味超标 2020-12-14 00:19

I have a string

let stringPlusString = TextBoxCal.text

I want to get the last character of stringPlusString. I do not want to

6条回答
  •  半阙折子戏
    2020-12-14 00:41

    Details

    • Swift 5.1, Xcode 11.2.1

    Solution

    extension String {
        func onlyLastCharacters(_ count: Int) -> String { return String(suffix(count)) }
        func onlyLastCharacters(_ count: Int, checkLength: Bool) -> String? {
            if checkLength {
                if self.count >= count { return onlyLastCharacters(count) }
                return nil
            }
            return String(suffix(count))
        }
    }
    

    Usage

    str.onlyLastCharacters(6)
    str.onlyLastCharacters(13, checkLength: true)
    

    Full sample

    Do not forget to paste here the solution code

    var testNumber = 0
    func show(original: String, modified: String?) {
        testNumber += 1
        if let string = modified {
            print("\(testNumber). Original: \"\(original)\", modified: \"\(string)\"")
        } else {
            print("\(testNumber). nil | count: nil")
        }
    }
    
    var str = "Hello world!"
    show(original: str, modified: str.onlyLastCharacters(6))
    show(original: str, modified: str.onlyLastCharacters(12))
    show(original: str, modified: str.onlyLastCharacters(13, checkLength: false))
    show(original: str, modified: str.onlyLastCharacters(13, checkLength: true))
    
    str = ""
    show(original: str, modified: str.onlyLastCharacters(10))
    show(original: str, modified: str.onlyLastCharacters(10, checkLength: true))
    show(original: str, modified: str.onlyLastCharacters(10, checkLength: false))
    

    Log

    1. Original: "Hello world!", modified: "world!"
    2. Original: "Hello world!", modified: "Hello world!"
    3. Original: "Hello world!", modified: "Hello world!"
    4. nil | count: nil
    5. Original: "", modified: ""
    6. nil | count: nil
    7. Original: "", modified: ""
    

提交回复
热议问题