在字符串中插入字符(Swift)

问题描述:

我有一个字符串“000”。我想将其更改为“0.00”。在字符串中插入字符(Swift)

我看了一下插入函数。

var str = "000" 
str.insert(".", at: str.endIndex) 

如何在结束索引之前得到2的索引?

我想:

str.insert(".", at: str.endIndex - 1) 

但这并没有在所有的工作。

+2

'str.insert(“。”,at:str.index(str.endIndex,offsetBy:-2))'。不要忘记确保您的字符串数> 2 –

+0

非常感谢! –

+0

https://stackoverflow.com/a/32466063/1187415 –

您还可以使用String的s character属性。它基本上是一个由String中的所有字符(duh)组成的数组。

所以,你会:

var str = "000" 

let index = str.characters.index(str.characters.startIndex, offsetBy: 1) //here you define a place (index) to insert at 
str.characters.insert(".", at: index) //and here you insert 

不幸的是,你必须首先创建一个index,如.insert不允许你指定使用Int位置。

+0

它是一个集合,而不是一个数组(否则你可以用一个Int索引它)。请注意,您的代码等同于'let index = str.index(str.startIndex,offsetBy:1); str.insert(“。”,at:index)'因为'String'将这些调用转发给它的字符视图。 –

+0

这非常整齐!但是没有办法首先创建索引,对吗?看起来很乏味。 – Marmelador