How to split string into only two parts with a given separator in Swift? [duplicate] - swift

This question already has answers here:
Swift split string at first match of a character
(3 answers)
Closed 5 years ago.
I have a requirement to split a string into 2 parts based on the first separator, for example the following source data:
1,Froederick,Frankenstien
2,Ludwig,Van,Beethoven
3,Anne Frank
Above each array element to be separated as following:
1st Component 2nd Component
1 Froederick,Frankenstien
2 Ludwig,Van,Beethoven
3 Anne Frank
I'm familiar with String.components(separatedBy: String) but I'm not sure how to only split once, as I get 3 components for 1st string, 4 components for 2nd string. Is there a Swifty (elegant) way of doing this?

You can use split on a characters property of a string and set the maxSplits parameter to 1. For example:
let splitString = "1,Froederick,Frankenstien".characters.split(separator: ",", maxSplits: 1)
The result is an array of CharacterView that need to be converted into strings for example using map along with init(_ characters:) initializer of a String.
let strings = splitString.map { String($0) }
This should produce an array ["1", "Froederick,Frankenstien"].

Related

I want to get Int value range 0-25 from a-z in Swift. And also reversely [duplicate]

This question already has answers here:
How do I cycle through the entire alphabet with Swift while assigning values?
(5 answers)
Closed 1 year ago.
I want to convert alphabets to numbers, in this way: a=0, b=1, c=2 ... z=25 in Swift.
I have an array of integers range 0-25. I want to get alphabets from the Int array.
If I have an array of characters, how can I get an array of Int?
//Create an array of UInt8 vaues:
var array = [UInt8]()
for _ in 1...20 {
array.append(UInt8.random(in: 0...25))
}
//Now map the array of values to characters 'a' to 'z'
let charArray = array.map {UnicodeScalar($0 + (Character("a").asciiValue ?? 0))}
charArray.forEach { print($0) }
//Now map the char array back to int values
let valueOfA = Character("a").asciiValue ?? 0
let charToUIntArray = charArray.map { (Character($0).asciiValue ?? 0) - valueOfA}
How to get string from ASCII code in Swift?
You can make your numbers match the right characters if you add an offset to your numbers and assign this number with the Character initializer to your character.
func getChar(number: Int)->Character{
return Character(UniCodeScalar(number+97))
}
The other way around you can use the asciiValue property.
(What's the simplest way to convert from a single character String to an ASCII value in Swift?)
After that you can loop through the array and use for example functions to convert.

How do I get the last value in a string separated by commas? [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 5 years ago.
I have this string
let data = 123,456,7,8,9,10
I want to extract the last value separated by a "," which in this case would be 10, and its not necessarily a two digit value.
I tried this:
var data = 123,456,7,8,9,10
data = data.last!
Use String method data.components(separatedBy:)
let data = "123,456,7,8,9,10"
let lastComponent = data.components(separatedBy: ",").last
print(lastComponent)

how can I join words from a String array to a single String, separated by a comma in Swift? [duplicate]

This question already has answers here:
How do I convert a Swift Array to a String?
(25 answers)
Closed 5 years ago.
I have an array of Strings in my Swift app. I want to display them in a label, each of them separated by ,. I tried this:
for hashtag in placeHashtags {
text = text + "\(hashtag), "
}
if (placeHashtags.count > 0){
let text1 = text.remove(at: text.index(before: text.endIndex-1))
text = text1.description
}
(the 2nd if is to remove the last comma), but then I do not see anything in my label.
How can I fix it?
You should Write this:
let array = ["Hi", "Hello", "How", "Are", "You", "Fine"]
let joined = array.joined(separator: ", ")

How to get the number of real words in a text in Swift [duplicate]

This question already has answers here:
Number of words in a Swift String for word count calculation
(7 answers)
Closed 5 years ago.
Edit: there is already a question similar to this one but it's for numbers separated by a specific character (Get no. Of words in swift for average calculator). Instead this question is about to get the number of real words in a text, separated in various ways: a line break, some line breaks, a space, more than a space etc.
I would like to get the number of words in a string with Swift 3.
I'm using this code but I get imprecise result because the number is get counting the spaces and new lines instead of the effective number of words.
let str = "Architects and city planners,are \ndesigning buildings to create a better quality of life in our urban areas."
// 18 words, 21 spaces, 2 lines
let components = str.components(separatedBy: .whitespacesAndNewlines)
let a = components.count
print(a)
// 23 instead of 18
Consecutive spaces and newlines aren't coalesced into one generic whitespace region, so you're simply getting a bunch of empty "words" between successive whitespace characters. Get rid of this by filtering out empty strings:
let components = str.components(separatedBy: .whitespacesAndNewlines)
let words = components.filter { !$0.isEmpty }
print(words.count) // 17
The above will print 17 because you haven't included , as a separation character, so the string "planners,are" is treated as one word.
You can break that string up as well by adding punctuation characters to the set of separators like so:
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let components = str.components(separatedBy: chararacterSet)
let words = components.filter { !$0.isEmpty }
print(words.count) // 18
Now you'll see a count of 18 like you expect.

Deleting Specific Substrings in Strings [Swift] [duplicate]

This question already has answers here:
Any way to replace characters on Swift String?
(23 answers)
Closed 5 years ago.
I have a string var m = "I random don't like confusing random code." I want to delete all instances of the substring random within string m, returning string parsed with the deletions completed.
The end result would be: parsed = "I don't like confusing code."
How would I go about doing this in Swift 3.0+?
It is quite simple enough, there is one of many ways where you can replace the string "random" with empty string
let parsed = m.replacingOccurrences(of: "random", with: "")
Depend on how complex you want the replacement to be (remove/keep punctuation marks after random). If you want to remove random and optionally the space behind it:
var m = "I random don't like confusing random code."
m = m.replacingOccurrences(of: "random ?", with: "", options: [.caseInsensitive, .regularExpression])