题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student.",则输出"student. a am I".
核心代码:
<pre><code>`
func reversePosition(strArr:inout [Character],begin:Int,end:Int) {
var low:Int = begin
var high:Int = end
while low < high {
swap(&strArr[low], &strArr[high])
low += 1
high -= 1
}
}
func reverseSentence(str:String) -> String {
var strArr:[Character] = [Character]()
for c in str.characters {
strArr.append(c)
}
reversePosition(strArr: &strArr, begin: 0, end: str.characters.count - 1)
var start:Int = 0
var end:Int = 0
while end < strArr.count {
if String(strArr[start]) == " " {
start += 1
end += 1
} else if String(strArr[end]) == " " {
reversePosition(strArr: &strArr, begin: start, end: end-1)
start = end
} else {
end += 1
}
}
return String(strArr)
}`</code></pre>
测试代码:
<pre><code>var orginalStr:String = "I am FlyElephant" var reverseString:ReverseString = ReverseString() var reverseResult:String = reverseString.reverseSentence(str: orginalStr) print("反转之后的字符串---\(reverseResult)---")
</code></pre>