我正在努力工作。如何删除2个字符,例如从'['到']'以及如何从字符串中删除“玻璃”字?
答案 0 :(得分:0)
您可能想尝试使用subStringWithRange
var str = "Hello, playground"
var startIndex = 0
var endIndex = 18
str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground"
然后,您可以将其分配给变量并完成剩下的工作。如果您需要进一步的帮助,请告诉我。积分here。您也可以在那里寻求支持。
希望有所帮助:)
答案 1 :(得分:0)
这是一个修改过的函数,允许多次删除。第一个函数处理单个删除。第二个函数将句子分成不同的句子,每个句子对应一个开始 - 结束组,然后在连接之前应用函数1以获得最终结果。我没有详尽地测试它。对于不存在的startString和/或endString,第一个函数受到保护。
函数deleteEnclosedString返回在startString中包含的字符串后剩余的字符串,并删除endString(包括)。
import UIKit
import Foundation
var str = "Hello, [play]ground [again]hi everybody [again]"
func deleteEnclosedString (s: String, s1:String, s2: String) -> String {
var returnedString = s
var x = s.componentsSeparatedByString(s1)
if (x[0] != s){ // startString present
let y = x[1].componentsSeparatedByString(s2)
if (y[0] != x[1]) { // start and endString present
returnedString = x[0]+y[1]
} else { // startString present, endString missing
returnedString = x[0]
}
} else { // startString missing
let y = s.componentsSeparatedByString(s2)
if (y[0] != s) { // no startString, endString present
returnedString = y[1]
} else { // no startString, endString missing
returnedString = y[0]
}
}
//println("returnedString: "+returnedString)
return returnedString
}
func deleteAllEnclosedStrings (s: String, startString s1:String, endString s2:String) -> String{
var returnedString = ""
var allSubstrings = s.componentsSeparatedByString(s1)
var strCount = allSubstrings.count
for i in (0 ..< strCount) {
var y = deleteEnclosedString(allSubstrings[i], s1 , s2)
returnedString = returnedString + y
}
return(returnedString)
}
// test cases
// start and end available
deleteAllEnclosedStrings(str, startString: "[", endString: "]") // Hello, ground hi everybody
// start but no end
deleteAllEnclosedStrings(str, startString: "[", endString: "}") // Hello, play]ground again]hi everybody again] and