如何在Swift 2.0中将字符插入字符串? [英] How to insert character into string in Swift 2.0?
本文介绍了如何在Swift 2.0中将字符插入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此函数接受一个类似324543
的Int并返回一个类似"$ 3245.43"的字符串
This function takes in an Int like 324543
and returns a String like "$3245.43"
我的尝试在下面,但是Swift 2不喜欢atIndex: 0
My attempt is below, but Swift 2 does not like atIndex: 0
我该如何代替在字符串中插入字符?
How would I go about inserting characters into a string instead?
func stylizeCents (cent: Int) -> String {
var styledCents = String(cent)
let dollarSign : Character = "$"
let dot : Character = "."
let count = styledCents.characters.count
styledCents.insert(dollarSign, atIndex: 0) // error
styledCents.insert(dot, atIndex: count-1) // error
}
推荐答案
此答案.
Swift 2.0
您可以使用字符串扩展名:
Swift 2.0
You can use a string extension:
extension String {
func insert(string:String,ind:Int) -> String {
return String(self.characters.prefix(ind)) + string + String(self.characters.suffix(self.characters.count-ind))
}
}
使用方式:
var url = "http://www.website.com"
url = url.insert("s", ind: 4) // outputs https://www.website.com
这篇关于如何在Swift 2.0中将字符插入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文