如何从特定索引的字符串中删除子字符串到 swift 中的某个长度
How to remove a substring from string of particular index to some length in swift
我有一个字符串,比方说,
var myString = "thisIsMyAutoGeneratedRandomString"
比方说,我想从索引 8 到 26 中删除一些字符。
我需要像
这样的输出
print(myString) //thisIsMyString --> This is what i want.
我试过 base1.remove(at: base1.index(i: String.Index, offsetBy: String.IndexDistance))
作为 base1.remove(at: base1.index(i: 8, offsetBy: 26))
但我收到类似警告
Cannot convert value of type 'Int' to expected argument type 'String.Index'
我尝试了很多东西,但没有运气。
你可以用 replacingOccurrences
var myString = "thisIsMyAutoGeneratedRandomString"
let parsed = myString.replacingOccurrences(of: "AutoGeneratedRandom", with: "")
print(myString) //"thisIsMyString"
var myString = "thisIsMyAutoGeneratedRandomString"
let ix = myString.startIndex // the index of 1st character
let ix2 = myString.index(ix, offsetBy: 8) // the index of 8th character
let ix3 = myString.index(ix, offsetBy: 26) // the index of 26th character
myString.removeSubrange(ix2...ix3)
print(myString) //thisIsMyString
使用 prefix
获得简单的解决方案
let firstPart = myString.prefix(8)
Swift解决方案前缀或let lastPart = date.suffix(16)
我有一个字符串,比方说,
var myString = "thisIsMyAutoGeneratedRandomString"
比方说,我想从索引 8 到 26 中删除一些字符。 我需要像
这样的输出print(myString) //thisIsMyString --> This is what i want.
我试过 base1.remove(at: base1.index(i: String.Index, offsetBy: String.IndexDistance))
作为 base1.remove(at: base1.index(i: 8, offsetBy: 26))
但我收到类似警告
Cannot convert value of type 'Int' to expected argument type 'String.Index'
我尝试了很多东西,但没有运气。
你可以用 replacingOccurrences
var myString = "thisIsMyAutoGeneratedRandomString"
let parsed = myString.replacingOccurrences(of: "AutoGeneratedRandom", with: "")
print(myString) //"thisIsMyString"
var myString = "thisIsMyAutoGeneratedRandomString"
let ix = myString.startIndex // the index of 1st character
let ix2 = myString.index(ix, offsetBy: 8) // the index of 8th character
let ix3 = myString.index(ix, offsetBy: 26) // the index of 26th character
myString.removeSubrange(ix2...ix3)
print(myString) //thisIsMyString
使用 prefix
获得简单的解决方案
let firstPart = myString.prefix(8)
Swift解决方案前缀或let lastPart = date.suffix(16)