How could I replace nth character of a String
with another one?
如何用另一个字符串替换字符串的第n个字符?
func replace(myString:String, index:Int, newCharac:Character) -> String {
// Write correct code here
return modifiedString
}
For example, replace("House", 2, "r")
should be equal to "Horse"
.
例如,replace(“House”,2,“r”)应该等于“Horse”。
10 个解决方案
#1
1
Please see NateCook answer for more details
详情请参阅NateCook回答
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
}
replace("House", 2, "r")
This is no longer valid and deprecated.
这不再有效和不赞成。
You can always use swift String
with NSString
.So you can call NSString
function on swift String
. By old stringByReplacingCharactersInRange:
you can do like this
可以使用带有NSString的swift字符串。你可以在swift字符串上调用NSString函数。由老的stringByReplacingCharactersInRange:你可以这样做。
var st :String = "House"
let abc = st.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r") //Will give Horse
#2
23
Solutions that use NSString
methods will fail for any strings with multi-byte Unicode characters. Here are two Swift-native ways to approach the problem:
使用NSString方法的解决方案对于任何具有多字节Unicode字符的字符串都将失败。这里有两个快速的方法来解决这个问题:
You can use the fact that a String
is a sequence of Character
to convert the string to an array, modify it, and convert the array back:
您可以使用字符串是字符序列的事实将字符串转换为数组,修改它,并将数组转换回:
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
}
replace("House", 2, "r")
// Horse
Alternately, you can step through the string yourself:
另外,您可以自己跨出字符串:
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
}
Since these stay entirely within Swift, they're both Unicode-safe:
因为它们完全在Swift内部,所以它们都是unico -safe:
replace("????????????????????", 2, "????")
// ????????????????????
#3
7
I've found this solution.
我发现这个解决方案。
var string = "Cars"
let index = string.index(string.startIndex, offsetBy: 2)
string.replaceSubrange(index...index, with: "t")
print(string)
// Cats
#4
7
In Swift 4 it's much easier.
在《Swift 4》中,这要容易得多。
let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)
This is an example:
这是一个例子:
let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)
where the result is
结果在哪里
Hell0, playground
The type of newString
is Substring. Both prefix
and dropFirst
return Substring
. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.
newString的类型是子字符串。前缀和dropFirst都返回子字符串。子字符串是字符串的一个切片,换句话说,子字符串非常快,因为您不需要为字符串的内容分配内存,但是使用与原始字符串相同的存储空间。
#5
1
I've expanded upon Nate Cooks answer and transformed it into a string extension.
我已经扩展了Nate Cooks answers,并将它转换成字符串扩展名。
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
}
}
usage:
用法:
let source = "House"
let result = source.replace(2,"r")
result is "Horse"
结果是“马”
#6
0
After looking at the Swift Docs, I managed to make this function:
在查看了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
}
Please note that this is untested, but it should give you the right idea.
请注意,这是未经测试的,但它应该给你正确的想法。
#7
0
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
}
I would prefer to pass a String
than a Character
though.
我更喜欢传递一个字符串而不是一个字符。
#8
0
I think what @Greg was trying to achieve with his extension is this:
我认为@Greg想要达到的目的是:
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!")
}
}
usage:
用法:
let source = "House"
source.replace(characterAt: 2, with: "r") //gives you "Horse"
#9
-1
Strings in swift don't have an accessor to read or write a single character. There's an excellent blog post by Ole Begemann describing how strings in swift work.
swift中的字符串没有读写单个字符的访问器。Ole Begemann写了一篇很棒的博文,描述了字符串在快速工作中的作用。
Note: the implementation below is wrong, read addendum
注意:下面的实现是错误的,请阅读附录。
So the right way is by taking the left part of the string up to the index -1
character, append the replacing character, then append the string from index + 1 up to the end:
因此,正确的方法是将字符串的左边部分加到索引-1字符,添加替换字符,然后将字符串从索引+ 1添加到末尾:
func myReplace(myString:String, index:Int, newCharac:Character) -> String {
var modifiedString: String
let len = countElements(myString)
if (index < len) && (index >= 0) {
modifiedString = myString.substringToIndex(index) + newCharac + myString.substringFromIndex(index + 1)
} else {
modifiedString = myString
}
return modifiedString
}
Note: in my implementation I chose to return the original string if the index is not in a valid range
注意:在实现中,如果索引不在有效范围内,我选择返回原始字符串
Addendum Thanks to @slazyk, who found out that my implementation is wrong (see comment), I am providing a new swift only version of the function.
感谢@slazyk发现我的实现是错误的(请参阅注释),我正在提供一个新的swift版本的函数。
func replace(myString:String, index:Int, newCharac:Character) -> String {
var modifiedString: String
if (index < 0) || (index >= countElements(myString)) {
modifiedString = myString
} else {
var start = myString.startIndex
var end = advance(start, index)
modifiedString = myString[start ..< end]
modifiedString += newCharac
start = end.successor()
end = myString.endIndex
modifiedString += myString[start ... end]
}
return modifiedString
}
@codester's answer looks very good, and it's probably what I would use myself. It would be interesting to know how performances compare though, using a fully swift solution and bridging to objective-c instead.
@codester的答案看起来很不错,这可能是我想用的。通过使用完全快速的解决方案和与objective-c的桥接,了解性能是如何比较的将是很有趣的。
#10
-1
Here is an efficient answer :
这里有一个有效的答案:
import Foundation
func replace(myString:String, index:Int, newCharac:Character) -> String {
return myString.substringToIndex(index-1) + newCharac + myString.substringFromIndex(index)
}
#1
1
Please see NateCook answer for more details
详情请参阅NateCook回答
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
}
replace("House", 2, "r")
This is no longer valid and deprecated.
这不再有效和不赞成。
You can always use swift String
with NSString
.So you can call NSString
function on swift String
. By old stringByReplacingCharactersInRange:
you can do like this
可以使用带有NSString的swift字符串。你可以在swift字符串上调用NSString函数。由老的stringByReplacingCharactersInRange:你可以这样做。
var st :String = "House"
let abc = st.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r") //Will give Horse
#2
23
Solutions that use NSString
methods will fail for any strings with multi-byte Unicode characters. Here are two Swift-native ways to approach the problem:
使用NSString方法的解决方案对于任何具有多字节Unicode字符的字符串都将失败。这里有两个快速的方法来解决这个问题:
You can use the fact that a String
is a sequence of Character
to convert the string to an array, modify it, and convert the array back:
您可以使用字符串是字符序列的事实将字符串转换为数组,修改它,并将数组转换回:
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
}
replace("House", 2, "r")
// Horse
Alternately, you can step through the string yourself:
另外,您可以自己跨出字符串:
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
}
Since these stay entirely within Swift, they're both Unicode-safe:
因为它们完全在Swift内部,所以它们都是unico -safe:
replace("????????????????????", 2, "????")
// ????????????????????
#3
7
I've found this solution.
我发现这个解决方案。
var string = "Cars"
let index = string.index(string.startIndex, offsetBy: 2)
string.replaceSubrange(index...index, with: "t")
print(string)
// Cats
#4
7
In Swift 4 it's much easier.
在《Swift 4》中,这要容易得多。
let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)
This is an example:
这是一个例子:
let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)
where the result is
结果在哪里
Hell0, playground
The type of newString
is Substring. Both prefix
and dropFirst
return Substring
. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.
newString的类型是子字符串。前缀和dropFirst都返回子字符串。子字符串是字符串的一个切片,换句话说,子字符串非常快,因为您不需要为字符串的内容分配内存,但是使用与原始字符串相同的存储空间。
#5
1
I've expanded upon Nate Cooks answer and transformed it into a string extension.
我已经扩展了Nate Cooks answers,并将它转换成字符串扩展名。
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
}
}
usage:
用法:
let source = "House"
let result = source.replace(2,"r")
result is "Horse"
结果是“马”
#6
0
After looking at the Swift Docs, I managed to make this function:
在查看了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
}
Please note that this is untested, but it should give you the right idea.
请注意,这是未经测试的,但它应该给你正确的想法。
#7
0
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
}
I would prefer to pass a String
than a Character
though.
我更喜欢传递一个字符串而不是一个字符。
#8
0
I think what @Greg was trying to achieve with his extension is this:
我认为@Greg想要达到的目的是:
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!")
}
}
usage:
用法:
let source = "House"
source.replace(characterAt: 2, with: "r") //gives you "Horse"
#9
-1
Strings in swift don't have an accessor to read or write a single character. There's an excellent blog post by Ole Begemann describing how strings in swift work.
swift中的字符串没有读写单个字符的访问器。Ole Begemann写了一篇很棒的博文,描述了字符串在快速工作中的作用。
Note: the implementation below is wrong, read addendum
注意:下面的实现是错误的,请阅读附录。
So the right way is by taking the left part of the string up to the index -1
character, append the replacing character, then append the string from index + 1 up to the end:
因此,正确的方法是将字符串的左边部分加到索引-1字符,添加替换字符,然后将字符串从索引+ 1添加到末尾:
func myReplace(myString:String, index:Int, newCharac:Character) -> String {
var modifiedString: String
let len = countElements(myString)
if (index < len) && (index >= 0) {
modifiedString = myString.substringToIndex(index) + newCharac + myString.substringFromIndex(index + 1)
} else {
modifiedString = myString
}
return modifiedString
}
Note: in my implementation I chose to return the original string if the index is not in a valid range
注意:在实现中,如果索引不在有效范围内,我选择返回原始字符串
Addendum Thanks to @slazyk, who found out that my implementation is wrong (see comment), I am providing a new swift only version of the function.
感谢@slazyk发现我的实现是错误的(请参阅注释),我正在提供一个新的swift版本的函数。
func replace(myString:String, index:Int, newCharac:Character) -> String {
var modifiedString: String
if (index < 0) || (index >= countElements(myString)) {
modifiedString = myString
} else {
var start = myString.startIndex
var end = advance(start, index)
modifiedString = myString[start ..< end]
modifiedString += newCharac
start = end.successor()
end = myString.endIndex
modifiedString += myString[start ... end]
}
return modifiedString
}
@codester's answer looks very good, and it's probably what I would use myself. It would be interesting to know how performances compare though, using a fully swift solution and bridging to objective-c instead.
@codester的答案看起来很不错,这可能是我想用的。通过使用完全快速的解决方案和与objective-c的桥接,了解性能是如何比较的将是很有趣的。
#10
-1
Here is an efficient answer :
这里有一个有效的答案:
import Foundation
func replace(myString:String, index:Int, newCharac:Character) -> String {
return myString.substringToIndex(index-1) + newCharac + myString.substringFromIndex(index)
}