如何将字符串的第n个字符替换为另一个字符

时间:2014-07-16 19:55:37

标签: string swift

如何将String第n个字符替换为另一个字符?

func replace(myString:String, index:Int, newCharac:Character) -> String {
    // Write correct code here
    return modifiedString
}

例如,replace("House", 2, "r")应该等于"Horse"

15 个答案:

答案 0 :(得分:26)

对于具有多字节Unicode字符的任何字符串,使用NSString方法的解决方案都将失败。以下是两种以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, "")
// 

答案 1 :(得分:13)

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

答案 2 :(得分:10)

我找到了这个解决方案。

fprintf(stderr, "%p", ret)

答案 3 :(得分:1)

我已经扩展了Nate Cooks的答案并将其转换为字符串扩展名。

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

结果是“马”

答案 4 :(得分: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"

答案 5 :(得分:0)

在查看Swift Docs后,我成功完成了这项功能:

//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
}

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

答案 6 :(得分:0)

Please see NateCook answer for more details

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

这已不再有效且已弃用。

您可以随时将StringNSString一起使用。因此,您可以在swift NSString上调用String函数。 通过旧的stringByReplacingCharactersInRange:你可以这样做

var st :String = "House"
let abc = st.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r") //Will give Horse

答案 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
}

我希望传递String而不是Character

答案 8 :(得分: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.

答案 9 :(得分:0)

        var s = "helloworld"
        let index = ((s.count) / 2) // index is 4
        let firstIndex = s.index(s.startIndex, offsetBy: index)
        let secondIndex = s.index(s.startIndex, offsetBy: index)
        s.replaceSubrange(firstIndex...secondIndex, with: "*")
        print("Replaced string is: \(s)") //OUTPUT IS: hell*world

这很好用索引替换字符串。

答案 10 :(得分:0)

extension String {
  subscript(index value: Int) -> Element {
    get {
        let i = index(startIndex, offsetBy: value)
        return self[i]
    } set {
        var array = Array(self)
        array[value] = newValue
        self = String(array)
    }
  }
}

用法:

var name = "Manas sharma"
print(name[index: 0])
name[index: 6] = "S"

答案 11 :(得分:0)

Swift 中的

String 类(直到 v5 或更高版本)是其他语言所称的 StringBuilder 类,出于性能原因,Swift 确实提供设置字符指数;如果您不关心性能,一个简单的解决方案可能是:

public static func replace(_ string: String, at index: Int, with value: String) {
    let start = string.index(string.startIndex, offsetBy: index)
    let end = string.index(start, offsetBy: 1)
    string.replaceSubrange(start..<end, with: value)
}

或者作为扩展:

extension String {
    public func charAt(_ index: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: index)];
    }

    public mutating func setCharAt(_ index: Int, _ new: Character) {
        self.setCharAt(index, String(new))
    }

    public mutating func setCharAt(_ index: Int, _ new: String) {
        let i = self.index(self.startIndex, offsetBy: index)
        self.replaceSubrange(i...i, with: new)
    }
}
<块引用>

注意上面如何需要调用index(...)方法将整数转换为实际索引!?看起来,Swift 实现 String 就像一个链表,其中 append(...) 真的很快,但即使找到索引(不做任何事情)也是一个线性时间操作(并根据连接计数变慢)。

答案 12 :(得分:0)

public void createEncodedSentence() {

    StringBuffer buff = new StringBuffer();
    int counter = 0;
    char a;

    for (int i = 0; i < sentence.length(); i++) {
        a = sentence.charAt(i);

        if (a == '.') {
            buff.append('*');
        }
        if (a != ' ' && a != '.') {
            counter++;
        }
        if (counter % 3 == 0) {
            buff.append("");
        }
        buff.append(sentence.charAt(i));


    }

    encodedSentence = buff.toString();

}

答案 13 :(得分:-1)

swift中的字符串没有读取或写入单个字符的访问者。 Ole Begemann描述了弦乐如何迅速发挥作用,这是一个很好的blog post

注意:下面的实现是错误的,请阅读附录

所以正确的方法是将字符串的左边部分转换为index -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
}

注意:在我的实现中,如果索引不在有效范围内,我选择返回原始字符串

附录感谢@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的答案看起来非常好,而且它可能是我自己使用的。 知道性能如何比较会很有趣,使用完全快速的解决方案并桥接到objective-c。

答案 14 :(得分:-1)

这是一个有效的答案:

import Foundation
func replace(myString:String, index:Int, newCharac:Character) -> String {
return myString.substringToIndex(index-1) + newCharac + myString.substringFromIndex(index)
}