3

my code is like the following:

let fileName = "/users/lezi/downloads/Zootopia.srt"
var srtFile = try? String(contentsOfFile: fileName)
let range = srtFile?.range(of: "00:00:59,825")
print(srtFile?[range!])
srtFile?.replaceSubrange(range!, with: "00:00:59,826")
print(srtFile?[range!])

I hope the "00:00:59,825" is replaced to "00:00:59,826", but the print is "Optional("\r\n\r\n2")\n", some characters just before "00:00:59,825"

9
  • 2
    Cannot reproduce. A (self-contained) minimal reproducible example is needed. Commented Jun 22, 2020 at 12:10
  • What language is the srt file for, maybe this is caused by some encoding issue? Commented Jun 22, 2020 at 12:21
  • I can reproduce this with a Chinese srt file, then I also get some garbage in the second print. Using replacingoccurenzces(of:with) seems to work though so it seems that this should be closed as a duplicate Commented Jun 22, 2020 at 12:34
  • @JoakimDanielson: Using range(of:) and replaceSubrange() should work as well (and is not equivalent to replacingOccurrences(of:with:)). I think it would be more helpful to figure out why the above code does not work as expected (instead of closing as a duplicate of a question about a different method). Commented Jun 22, 2020 at 12:40
  • @MartinR You are right. The replaceSubrange function works fine, it is the second print(srtFile?[range]) statement that doesn't work. If I print the whole file I can see the change. So I guess this then should be closed as "Can not reproduce"? Commented Jun 22, 2020 at 12:49

2 Answers 2

5

You can try using replacingOccurrences(of:with:). Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string

sample example :

let str = "Swift 4.0 is the best version of Swift to learn, so if you're starting fresh you should definitely learn Swift 4.0."
let replaced = str.replacingOccurrences(of: "4.0", with: "5.0")
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but if that's the answer, the question is then a duplicate of stackoverflow.com/questions/24200888/…
replacingOccurrences and replaceSubrange both works, but the range got before replaceSubrange seems invalid after replaceSubrange is executed
1

Regardless of use case. The common syntax to replace the substring is:

str.replacingOccurrences(of: "replace_this", with: "with_this")

where replace_thisis the text string you want to replace and ```with_this`` is the new sub-string to insert.

2 Comments

Thank you, but if that's the answer, the question is then a duplicate of stackoverflow.com/questions/24200888/…
Yes. It is a method of String.NSString not a method of String. Makes it hard to find!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.