How to Return a First Word from a String in Swift

Get the first word in a String of words & spaces - Substring first word before space

If your string is heavy, componentsSeparatedByString() tends to be faster.

Swift 2:

var date = "1,340d 1h 15m 52s"
if let first = date.componentsSeparatedByString(" ").first {
// Do something with the first component.
}

Swift 3/4/5:

if let first = date.components(separatedBy: " ").first {
// Do something with the first component.
}

How to get the first word before a dash in Swift?

Use index(of:) and substring(to:).

Following your comment, I've also added an example to get the second year.

let str = "2007-2016"

if let idx = str.characters.index(of: "-") {
let year1 = str.substring(to: idx)
print(year1)
let year2 = str.substring(from: str.index(after: idx))
print(year2)
}

Getting first letter from the string of first two words

Try this. It separates the string into array of string and removes nil. So if the string has double space it filters that. Make sure that the string has minimum 2 words.

if let bakery = filtered?[indexPath.row]{
let stringInput = bakery.fruitsname
if stringInput.components(separatedBy: " ").count >= 2 {
let stringNeed = (stringInput.components(separatedBy: " ").map({ $0.characters.first }).flatMap({$0}).reduce("", { String($0) + String($1) }) as NSString).substring(to: 2)
print(stringNeed)
}
}

How to get the first characters in a string? (Swift 3)

If you did not want to use range

let onlineString:String = "<ONLINE> Message with online tag!"

let substring:String = onlineString.components(separatedBy: " ")[0]

print(substring) // <ONLINE>

How to get the first character of each word in a string?

You can try this code:



let stringInput = "First Last"
let stringInputArr = stringInput.components(separatedBy:" ")
var stringNeed = ""

for string in stringInputArr {
stringNeed += String(string.first!)
}

print(stringNeed)

If have problem with componentsSeparatedByString you can try seperate by character space and continue in array you remove all string empty.

Hope this help!

accessing core data to return first word in swift

Retrieve the id from the array using the given indexPath

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let id = friends[indexPath.row].studentID
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.removeRecord(id: id)
}


Related Topics



Leave a reply



Submit