本文介绍了颠倒字符串值的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数可以反转字符串值的显示顺序。
我是Swift的新手,我试图理解它的逻辑。 !pleh值会变成帮助!,这是怎么回事?
谢谢

I have the following function which reverses a string value's display order.I'm new to Swift and I'm trying to understand it's logic. What is going on with the '!pleh' value that it turns into 'Help!' ?Thanks

func reverse(_ s: String) -> String {
 var str = ""
 for character in s.characters {
    str = "\(character)" + str
 }
 return str
}
print (reverse("!pleH"))


推荐答案

在线评论,

Commented inline,

func reverse(_ s: String) -> String {
 var str = ""
 //.characters gives the character view of the string passed. You can think of it as array of characters.
 for character in s.characters {
    str = "\(character)" + str
    //This will help you understand the logic.
    //!+""
    //p+!
    //l+p! ... goes this way
    print ( str)
 }
 return str
}
print (reverse("!pleH"))

这篇关于颠倒字符串值的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:40