请原谅我,因为我是这种语言的新手。
编辑:有没有办法扭转数组元素的位置?
我正在尝试创建一个函数来测试给定的输入,如果它是一个回文。我试图避免使用reverse()
来使用函数let word = ["T","E","S","T"]
var temp = [String]()
let index_count = 3
for words in word{
var text:String = words
print(text)
temp.insert(text, atIndex:index_count)
index_count = index_count - 1
}
答案 0 :(得分:3)
您的方法可以用于反转数组。但你必须这样做 将原始数组的每个元素插入开始位置 目标数组(将其他元素移动到末尾):
// Swift 2.2:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
reversed.insert(char, atIndex: 0)
}
print(reversed) // ["T", "S", "E", "T"]
// Swift 3:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
reversed.insert(char, at: 0)
}
print(reversed) // ["T", "S", "E", "T"]
可以直接对字符串的字符进行相同的操作:
// Swift 2.2:
let word = "TEST"
var reversed = ""
for char in word.characters {
reversed.insert(char, atIndex: reversed.startIndex)
}
print(reversed) // "TSET"
// Swift 3:
let word = "TEST"
var reversed = ""
for char in word.characters {
reversed.insert(char, at: reversed.startIndex)
}
print(reversed)
答案 1 :(得分:1)
斯威夫特 5
impl<'a, T: 'a> RefIterable<'a> for Vec<T> {
type Item = T;
type Iter = std::slice::Iter<'a, T>;
fn refs(&'a self) -> std::slice::Iter<'a, T> {
self.as_slice().iter()
}
}
答案 2 :(得分:0)
这是我的解决方案:
extension String {
func customReverse() -> String {
var chars = Array(self.characters)
let count = chars.count
for i in 0 ..< count/2 {
swap(&chars[i], &chars[count - 1 - i])
}
return String(chars)
}
}
let input = "abcdef"
let output = input.customReverse()
print(output)
您可以尝试here。
答案 3 :(得分:0)
static func reverseString(str : String) {
var data = Array(str)
var i = 0// initial
var j = data.count // final
//either j or i for while , data.count/2 buz only half we need check
while j != data.count/2 {
print("befor i:\(i) j:\(j)" )
j = j-1
data.swapAt(i, j) // swapAt API avalible only for array in swift
i = i+1
}
print(String(data))
}
答案 4 :(得分:-1)
let word = "aabbaa"
let chars = word.characters
let half = chars.count / 2
let leftSide = Array(chars)[0..<half]
let rightSide = Array(chars.reverse())[0..<half]
let palindrome = leftSide == rightSide
var palindrome = true
let chars = Array(word.characters)
for i in 0 ..< (chars.count / 2) {
if chars[i] != chars[chars.count - 1 - i] {
palindrome = false
break
}
}
print(palindrome)
答案 5 :(得分:-1)
另一种逆转解决方案:
var original : String = "Test"
var reversed : String = ""
var c = original.characters
for _ in 0..<c.count{
reversed.append(c.popLast()!)
}
它只是附加弹出的旧字符串的每个元素,从最后一个元素开始并朝着第一个元素开始