如何用另一个字符替换字符串中的第n个字符

37

我该如何替换一个字符串的第n个字符为另一个字符?

func replace(myString:String, index:Int, newCharac:Character) -> String {
    // Write correct code here
    return modifiedString
}
例如,replace("House", 2, "r") 应该等于 "Horse"

这与这个问题类似,它也有答案。 https://dev59.com/a1nUa4cB1Zd3GeqPcae5 - Shashi Jeevan M. P.
3
相似的问题,但是不同的语言:Swift 不是 JavaScript。 - Martin R
15个回答

38

使用NSString方法的解决方案对于任何包含多字节Unicode字符的字符串都会失败。下面是两种本地Swift方法来解决这个问题:

您可以利用StringCharacter序列的事实,将字符串转换为数组,进行修改,然后再将数组转换回字符串:

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, "")
// 

String.characters()在Swift 4中已被弃用。有什么替代方法吗? - Awais Fayyaz
在Swift 4中,你可以将var chars = Array(myString.characters)更改为var chars = Array(myString)来解决弃用警告。来源:https://dev59.com/XF8e5IYBdhLWcg3wRIpQ#25921323 - Liron Yahdav
@LironYahdav 请在回答中添加这个。谢谢 - Awais Fayyaz
这会导致至少1个副本(如果不是更多),而Swift团队之所以不允许该功能,只是为了防止这种情况发生!!有兴趣获取无副本版本的人可以查看我的答案(https://dev59.com/YWAf5IYBdhLWcg3wUBT4#67653964)(仅编辑链接列表中的一个节点,其内部可能是String,而不是复制)。 - Top-Master

22

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的类型是SubstringprefixdropFirst都返回Substring。 Substring是字符串的一部分,换句话说,子字符串很快,因为您不需要为字符串内容分配内存,而是使用与原始字符串相同的存储空间。


如何对“Substring”执行相同的操作? - Noah Wilder
完全一样。您可以将示例的第一行替换为 let oldString: Substring = "Hello,playground",这样就可以正常工作了。 - Luca Torella

22
我找到了这个解决方案。
var string = "Cars"
let index = string.index(string.startIndex, offsetBy: 2)
string.replaceSubrange(index...index, with: "t")
print(string)
// Cats

8

请查看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
}

针对 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

什么是bridgeToObjectiveC()? - kumaresh
这会导致至少1个副本(如果不是更多),而Swift团队之所以不允许该功能,只是为了防止这种情况发生!!有兴趣获取无副本版本的人可以查看我的答案(https://dev59.com/YWAf5IYBdhLWcg3wUBT4#67653964)(仅编辑链接列表中的一个节点,其内部可能是String,而不是复制)。 - Top-Master

2

修改现有字符串的方法:

    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) 

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

1
我认为@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!")
    }
}

使用方法:

let source = "House"
source.replace(characterAt: 2, with: "r") //gives you "Horse"

1

我扩展了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")

结果是“马”。

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
}

我更倾向于传递一个字符串而不是一个字符。


0

这里有一个替换单个字符的方法:

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.

0

在查看了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
}

请注意,这是未经测试的,但它应该能够给你正确的想法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接