从字符串中删除两个字符

时间:2017-09-06 15:27:04

标签: swift

以下是我的“服务”变量。我想从中删除前2个字符。那就是我想用“”替换“,”

let services = ", EXTERNAL SERVICE, INTERNAL SERVICE"

我想产生以下结果

let services = "EXTERNAL SERVICE, INTERNAL SERVICE"

怎么做?

3 个答案:

答案 0 :(得分:0)

如果您始终要删除前两个字符,请使用String.substring(from:)

let services = ", EXTERNAL SERVICE, INTERNAL SERVICE"
let correctServices = services.substring(from: services.index(services.startIndex, offsetBy: 2))
  

输出:“外部服务,内部服务”

答案 1 :(得分:0)

这是一个解决方案,它基于这样的假设,即字符串由一个由", "分隔的数组或循环中的字符串连接组成。

它将字符串转换为数组,删除空项并将字符串转换回字符串

let services = ", EXTERNAL SERVICE, INTERNAL SERVICE"
               .components(separatedBy: ", ")
               .filter{ !$0.isEmpty }
               .joined(separator: ", ")

我认为最好的解决方案是以前通过字符串连接来组成services

答案 2 :(得分:0)

看起来你想从头开始摆脱无关的角色,也许从最后开始。在你的情况下,你有两个字符,但有一个更通用的方式 - 这是修剪。这是来自游乐场

// Your original string
let string = ", EXTERNAL SERVICE, INTERNAL SERVICE"

// Create a character set for things to exclude - in this case whitespace, newlines and punctuation
let charset = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)

// Trimming removes the characters from the characterset from the beginning and the end of the string
let trimmedString = string.trimmingCharacters(in: charset) // -> "EXTERNAL SERVICE, INTERNAL SERVICE"