有人知道我在下面运行代码时出现以下错误的原因吗?
错误:无法指定类型' String.CharacterView.index'的值输入' Int'
START TRANSACTION;
select [col1] [col3] from [table1] where [col1] = 0 ;
UPDATE [table1] SET [col1] = 1 where [col1] = 0;
COMMIT;
更新
我尝试将let lastIndex更改为var lastIndex但没有运气
答案 0 :(得分:1)
这是解决问题的简单方法:
let input = "find the longest word in the problem description";
let longest = input
.characters //get the input characters
.split(separator:" ", //split by spaces
maxSplits: 1000, //max number of splits
omittingEmptySubsequences: true) //omit "" splits
.map(String.init) //make new strings from the characters
.max{$0.characters.count < $1.characters.count} //get longest length word
print(longest)
答案 1 :(得分:0)
您无法比较lastCheck
(Int
}和lastIndex
(Index
)。
你必须转换它:
var problem = "find the longest word in the problem description"
var last = problem.characters.last
let lastIndex = problem.characters.endIndex;
print(last);
var words:[String] = [String]();
var word:String = "";
var lastCheck:Int = 0;
for i in problem.characters{
lastCheck = lastCheck + 1
let lastIndexInt = problem.characters.startIndex.distanceTo(end: lastIndex) // new
if i != " "{
word = word + String(i)
}
else if lastCheck = lastIndex{
words.append(word);
}
else if i == " "{
words.append(word)
word = ""
}
}
print(words)
答案 2 :(得分:0)
String.CharacterView.Index
是struct
,但不是Int
。因此,您无法为Int
变量分配String.CharacterView.Index
。这是正常的。
您必须将@转换为@ Amomchilov的答案,或使用索引:
...
var lastCheck:String.CharacterView.Index = problem.startIndex
for i in problem.characters {
lastCheck = lastCheck.advancedBy(1)
...
}
无论如何,为了找到一个短语的最长单词,你可以使用Swift的builtIn函数来获取所有单词,然后比较它们的长度。 例如:
let str = "find the longest word in the problem description"
var longestWord : String?
str.enumerateSubstringsInRange(str.startIndex..<str.endIndex, options:.ByWords) {
(substring, substringRange, enclosingRange, value) in
if let _subString = substring {
if longestWord == nil || longestWord!.characters.count < _subString.characters.count {
longestWord = _subString
}
}
}
答案 3 :(得分:0)
轻松获取句子中的所有单词
var problem = "find the longest word in the problem description"
problem.enumerateSubstrings(in: (problem.range(of: problem))!, options: NSString.EnumerationOptions.byWords, { (substring, substringRange, enclosingRange, stop) -> () in
print(substring)
})
轻松获得句子中最长的单词
var longestWord = ""
problem.enumerateSubstrings(in: (problem.range(of: problem))!, options: NSString.EnumerationOptions.byWords, { (substring, substringRange, enclosingRange, stop) -> () in
if longestWord.characters.count < substring?.characters.count{
longestWord = substring!
}
})
print(longestWord)
注意:代码参考Swift 3.对于较低版本会有一些语法更改。让我知道你是否需要相同的较低版本。