我该如何替换一个字符串的第n个字符为另一个字符?
func replace(myString:String, index:Int, newCharac:Character) -> String {
// Write correct code here
return modifiedString
}
例如,replace("House", 2, "r")
应该等于 "Horse"
。我该如何替换一个字符串的第n个字符为另一个字符?
func replace(myString:String, index:Int, newCharac:Character) -> String {
// Write correct code here
return modifiedString
}
例如,replace("House", 2, "r")
应该等于 "Horse"
。使用NSString
方法的解决方案对于任何包含多字节Unicode字符的字符串都会失败。下面是两种本地Swift方法来解决这个问题:
您可以利用String
是Character
序列的事实,将字符串转换为数组,进行修改,然后再将数组转换回字符串:
func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
var chars = Array(myString) // gets an array of characters
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}
replace("House", 2, "r")
// Horse
或者,您可以自己逐个字符地遍历该字符串:
func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
var modifiedString = String()
for (i, char) in myString.characters.enumerate() {
modifiedString += String((i == index) ? newChar : char)
}
return modifiedString
}
由于这些内容完全在Swift内部,因此它们都是Unicode安全的:
replace("", 2, "")
//
var chars = Array(myString.characters)
更改为var chars = Array(myString)
来解决弃用警告。来源:https://dev59.com/XF8e5IYBdhLWcg3wRIpQ#25921323 - Liron Yahdav在Swift 4中,这变得更加容易。
let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)
这是一个例子:
let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)
结果在哪里
Hell0, playground
newString
的类型是Substring
。 prefix
和dropFirst
都返回Substring
。 Substring是字符串的一部分,换句话说,子字符串很快,因为您不需要为字符串内容分配内存,而是使用与原始字符串相同的存储空间。
let oldString: Substring = "Hello,playground"
,这样就可以正常工作了。 - Luca Torellavar string = "Cars"
let index = string.index(string.startIndex, offsetBy: 2)
string.replaceSubrange(index...index, with: "t")
print(string)
// Cats
func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
var chars = Array(myString.characters) // gets an array of characters
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}
针对 Swift 5
func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
var chars = Array(myString) // gets an array of characters
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}
replace("House", 2, "r")
NSString
的Swift String
。因此,您可以在Swift String
上调用NSString
函数。stringByReplacingCharactersInRange:
,您可以像这样操作。var st :String = "House"
let abc = st.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r") //Will give Horse
修改现有字符串的方法:
extension String {
subscript(_ n: Int) -> Character {
get {
let idx = self.index(startIndex, offsetBy: n)
return self[idx]
}
set {
let idx = self.index(startIndex, offsetBy: n)
self.replaceSubrange(idx...idx, with: [newValue])
}
}
}
var s = "12345"
print(s[0])
s[0] = "9"
print(s)
mutating func replace(characterAt index: Int, with newChar: Character) {
var chars = Array(characters)
if index >= 0 && index < self.characters.count {
chars[index] = newChar
let modifiedString = String(chars)
self = modifiedString
} else {
print("can't replace character, its' index out of range!")
}
}
使用方法:
let source = "House"
source.replace(characterAt: 2, with: "r") //gives you "Horse"
我扩展了Nate Cook的回答并将其转换为字符串扩展。
extension String {
//Enables replacement of the character at a specified position within a string
func replace(_ index: Int, _ newChar: Character) -> String {
var chars = Array(characters)
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}
}
使用方法:
let source = "House"
let result = source.replace(2,"r")
func replace(myString:String, index:Int, newCharac:Character) -> String {
var modifiedString = myString
let range = Range<String.Index>(
start: advance(myString.startIndex, index),
end: advance(myString.startIndex, index + 1))
modifiedString.replaceRange(range, with: "\(newCharac)")
return modifiedString
}
我更倾向于传递一个字符串而不是一个字符。
这里有一个替换单个字符的方法:
var string = "This is the original string."
let offset = 27
let index = string.index(string.startIndex, offsetBy: offset)
let range = index...index
print("ORIGINAL string: " + string)
string.replaceSubrange(range, with: "!")
print("UPDATED string: " + string)
// ORIGINAL string: This is the original string.
// UPDATED string: This is the original string!
这也适用于多字符字符串:
var string = "This is the original string."
let offset = 7
let index = string.index(string.startIndex, offsetBy: offset)
let range = index...index
print("ORIGINAL string: " + string)
string.replaceSubrange(range, with: " NOT ")
print("UPDATED string: " + string)
// ORIGINAL string: This is the original string.
// UPDATED string: This is NOT the original string.
在查看了Swift文档之后,我成功地创建了这个函数:
//Main function
func replace(myString:String, index:Int, newCharac:Character) -> String {
//Looping through the characters in myString
var i = 0
for character in myString {
//Checking to see if the index of the character is the one we're looking for
if i == index {
//Found it! Now instead of adding it, add newCharac!
modifiedString += newCharac
} else {
modifiedString += character
}
i = i + 1
}
// Write correct code here
return modifiedString
}