简体   繁体   English

如何在Swift中检查字符串的最后一个字符是否等于“ a”

[英]How do I check if last character of a string equals to “a” in Swift

For example: 例如:

I want to get the text/word by user and if this word's last character is "a" I want to change this "a" to "b"...How should i have to write this code? 我想按用户获取文本/单词,如果该单词的最后一个字符是“ a”,我想将此“ a”更改为“ b” ...我应该如何编写此代码?

let getText = txtWord.text

if

......

You need to check if the last char is "a" . 您需要检查最后一个字符是否为"a"

If so just drop the last char and append the new one. 如果是这样,只需删除最后一个字符并追加新的字符。

var text = txtWord.text

if text.characters.last == "a" {
    text = String(text.characters.dropLast()) + "b"
}

swift 4: 迅速4:

let abc:String = txtWord.text
var newABC:String!
if abc.suffix(1) == 'a'{

   newABC = abc + "b"
   print("Done")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM