当前位置:  开发笔记 > 编程语言 > 正文

颠倒字符串值的顺序

如何解决《颠倒字符串值的顺序》经验,为你挑选了5个好方法。



1> Fangming..:

在swift 4.0中,直接调用reversed字符串将完成工作

let str = "abc"
String(str.reversed()) // This will give you cba



2> dfri..:

该函数reversed(_:)迭代Character所提供的字符串中的每一个s,并以相反的顺序简单地将它们集中在一起.

// 1st pass in the 'for' loop:
//    @ start of iteration: 'str' equals ""
//    update value of 'str' according to
//    str = aCharacterAsString + str = "!" + ""

// 2nd pass in the 'for' loop:
//    @ start of iteration: str equals "!"
//    update value of 'str' according to
//    str = anotherCharacterAsString + str = "p" + "!"

// 3rd pass in the 'for' loop:
//    @ start of iteration: str equals "p!"
//    update value of 'str' according to
//    str = yetAnotherCharacterAsString + str = "l" + "p!"

// and so on ...

// after end of 'for' loop: str == "help!"

// this value of 'str' is then return to callee (which prints it)

一个更简单的方法是使用reversed()CharacterView对的String实例:

let str = "!pleH"
print(String(str.characters.reversed())) // Help!

Swift 4您可以直接在字符串中使用它

let str = "!pleH"
print(String(str.reversed())) // Help!


@WiktorStribiżew他的答案也可能只是这个答案的评论

3> Vignesh..:

内联注释,

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"))



4> abhimuralidh..:

注意:如果您不想使用reversed()内置功能,则可以使用以下代码。[面试要求]

在字符串上使用高阶函数“ Reduce ” 的一线。

extension String {
func reverse() -> String  { return self.reduce("") { "\($1)" + $0 } }
}



5> Sourabh Kumb..:
var string = "My,playground and my Swift" 
var reverseString = ""  
for str in string { 
    reverseString.insert(str, at: reverseString.startIndex) 
}  
print(reverseString)

推荐阅读
谢谢巷议
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有