如何修复此代码,以便我不再收到错误。我得到的错误是致命错误:数组索引超出范围。代码检查字符串中有多少“x”和“o”
var input = "xxxoxoooxoxo"
var inputString = Array(input.characters)
var XString = ""
var OString = ""
for var i = 0; i <= inputString.count; ++i {
if inputString[i] == "x" {
XString.append(inputString[i])
}
else if inputString[i] == "o" {
OString.append(inputString[i])
}
}
if XString.characters.count == OString.characters.count {
print("equal")
}
else {
print("Not Equal")
}
感谢您的帮助。
答案 0 :(得分:3)
替换此
for var i = 0; i <= inputString.count; ++i
用这个:
for var i = 0; i < inputString.count; ++i
数组是零索引的。这意味着第一个元素的索引为0.第二个元素的索引为1. ....最后一个元素的索引为array.count-1
。
答案 1 :(得分:3)
@dasdom是正确的。但这是一种更快捷的方式:
// input string
var input = "ooooxxxxxxxoxoooxoxo"
// difference between number of x's and number of o's
var diff = 0
// perform this function for each character in `input.characters`:
input.characters.forEach {
switch $0 // $0 is the argument to our function (unnamed)
{
case "x": diff += 1 // x's are +1
case "o": diff -= 1 // o's are -1
default: fatalError() // we expect only 'x' or 'o'... if we get something else, just crash
}
}
// use the ternary (?:) operator to print the answer.
// (<result> = <condition> ? <if-true value> : <if-false value>)
print( diff == 0 ? "equal" : "not equal" )
一个较短的版本,灵感来自@ Eendje的答案:)
print( input.characters.reduce(0) { $0 + [ "x":1, "o":-1 ][ $1 ]! } != 0 ? "not" : "", "equal" )
答案 2 :(得分:2)
虽然每个人都给你一个替代方案,但我认为这也是一个很好的补充:
var input = "xxxxxoxoooxoxo"
您可以使用filter
:
let xCount = input.characters.filter { $0 == "x" }.count
let oCount = input.characters.filter { $0 == "o" }.count
print( xCount == oCount ? "equal" : "not equal" )
在您的情况下,使用reduce
会更有效,而且更短:
let result = input.characters.reduce(0) { $0 + ($1 == "x" ? 1 : -1) }
print(result == 0 ? "equal" : "not equal") // not equal
仅当您确定input
仅包含x
和o
时才会这样做。如果没有,那么您必须将评估更改为:
{ $0 + ($1 == "x" ? 1 : $1 == "o" ? -1 : 0) }
答案 3 :(得分:0)
您正在枚举传递数组的范围。请改用它。
for var i = 0; i < inputString.count; ++i {
或者你可以使用这个更惯用的代码:
var input = "xxxoxoooxoxo"
var xString = 0
var oString = 0
for c in input.characters {
if c == "x" {
xString++
}
else if c == "o" {
oString++
}
}
if oString == xString {
print("equal")
}
else {
print("Not Equal")
}