如何在 Swift 中的字符串中的特定索引处添加字符 [英] How to add a character at a particular index in string in Swift

查看:18
本文介绍了如何在 Swift 中的字符串中的特定索引处添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 中有一个这样的字符串:

I have a string like this in Swift:

var stringts:String = "3022513240"

如果我想把它改成这样的字符串:"(302)-251-3240",我想在索引0处添加括号,我该怎么做?

If I want to change it to string to something like this: "(302)-251-3240", I want to add the partheses at index 0, how do I do it?

在 Objective-C 中是这样完成的:

In Objective-C, it is done this way:

 NSMutableString *stringts = "3022513240";
 [stringts insertString:@"(" atIndex:0];

如何在 Swift 中做到这一点?

How to do it in Swift?

推荐答案

如果你将它声明为 NSMutableString 那么这是可能的,你可以这样做:

If you are declaring it as NSMutableString then it is possible and you can do it this way:

let str: NSMutableString = "3022513240)"
str.insert("(", at: 0)
print(str)

输出是:

(3022513240)

如果你想在开始时添加:

If you want to add at starting:

var str = "3022513240)"
str.insert("(", at: str.startIndex)

如果要在最后一个索引处添加字符:

If you want to add character at last index:

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

如果你想在特定索引处添加:

And if you want to add at specific index:

str.insert("(", at: str.index(str.startIndex, offsetBy: 2))

这篇关于如何在 Swift 中的字符串中的特定索引处添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆