Reversing a string in Swift [duplicate] - swift

This question already has answers here:
Reversing the order of a string value
(13 answers)
Closed 5 years ago.
Needed to reverse a swift string, managed to do so with this.
var str = "Hello, playground"
let reactedText = str.characters.reversed()
let nowBackwards = Array(reactedText)
let answer = String(nowBackwards)
And since I find nothing on SO in the subject I post it for some positive votes :) or indeed a better [shorter, as in different] solution.

Assuming you are using Swift 4 :
let string = "Hello, playground"
let reversedString = String(string.reversed())

Since in Swift 4, Strings are Character arrays again, you can call reversed on the String itself and the result will be of type [Character], from which you can initialize a String.
let stringToBeReversed = "Hello, playground"
let reversedString = String(stringToBeReversed.reversed()) //"dnuorgyalp ,olleH"

reversed method is available in String library
let str = "Hello, world!"
let reversed = String(str.reversed())
print(reversed)

Related

Swift filter map reduce which option [duplicate]

This question already has answers here:
How to get the first character of each word in a string?
(11 answers)
Closed 1 year ago.
I have quick question about Swift algorithm, assuming I have a string “New Message” which option I need to use to get just initials NM ?
I would use map to get the first character of each word in the string, then use reduce to combine them.
let string = "New Message"
let individualWords = string.components(separatedBy: " ")
let firstCharacters = individualWords.map { $0.prefix(1) }.reduce("", +)
print("firstCharacters is \(firstCharacters)")
Result:
firstCharacters is NM
Edit: Per #LeoDabus' comment, joined is more concise than reduce("", +), and does the same thing.
let firstCharacters = individualWords.map { $0.prefix(1) }.joined()

How to replace a substring in a string in Swift [duplicate]

This question already has answers here:
Any way to replace characters on Swift String?
(23 answers)
Closed 2 years ago.
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"
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.
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")

String Convert into double in swift 4.1 [duplicate]

This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 4 years ago.
let getLongijson: String = "67.0011"
let getlatijson: String = "24.8607"
let jsonlong = (getLongijson as NSString).doubleValue
let jsonlat = (getlatijson as NSString).doubleValue
Error i am Facing this
Cannot use instance member 'getLongijson' within property initializer; property initializers run before 'self' is available
You like this to convert String into Double:
let getLongijson: String = "67.0011"
let getlatijson: String = "24.8607"
let jsonlong = Double(getLongijson)
let jsonlat = Double(getlatijson)

Efficient way to find all instances of Substring within a Swift String [duplicate]

This question already has answers here:
Swift find all occurrences of a substring
(7 answers)
Closed 5 years ago.
Swift 4 apparently has introduced a lot of new changes to String. I'm wondering if there is now a built-in method for finding all instances of a substring within a String.
Here's the kind of thing I'm looking for:
let searchSentence = "hello world, hello"
let wordToMatch = "hello"
let matchingIndexArray = searchSentence.indices(of: "wordToMatch")
'matchingIndexArray' would then be [0, 13]
import Foundation
let searchSentence = "hello world, hello"
var searchRange = searchSentence.startIndex..<searchSentence.endIndex
var ranges: [Range<String.Index>] = []
let searchTerm = "hello"
while let range = searchSentence.range(of: searchTerm, range: searchRange) {
ranges.append(range)
searchRange = range.upperBound..<searchRange.upperBound
}
print(ranges.map { "(\(searchSentence.distance(from: searchSentence.startIndex, to: $0.lowerBound)), \(searchSentence.distance(from: searchSentence.startIndex, to: $0.upperBound)))" })
outputs:
["(0, 5)", "(13, 18)"]

Cannot convert value of type Substring to expected argument type String - Swift 4

Trying to get substring of String and append it to array of Strings:
var stringToSplit = "TEST TEXT"
var s = [String]()
let subStr = anotherString[0 ..< 6]
s.append(subStr) // <---- HERE I GET THE ERROR
As #Leo Dabus mentioned, you need to initialize a new String with your substring:
Change:
s.append(subStr)
To:
s.append(String(subStr))
my two cents for serro in different context.
I was trying to get an array of "String" splitting a string.
"split" gives back "Substring", for efficiency reason (as per Swift.org litre).
So I ended up doing:
let buffer = "one,two,three"
let rows = buffer.split(separator:",")
let realStrings = rows.map { subString -> String in
return String(subString)
}
print(realStrings)
Ape can help someone else.