Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I have a string that has words and spaces, "2h 3m 1s". I want to extract 2h out of it; so get everything before first space.

var date = "1,340d 1h 15m 52s"  // I want to extract "1,340d".

What is the best practice of doing it? What substring function is the best approach?

like image 267
senty Avatar asked Dec 17 '15 11:12

senty


People also ask

How do I get the first word of a string in SQL?

SELECT SUBSTRING_INDEX(yourColumnName,' ',1) as anyVariableName from yourTableName; In the above query, if you use -1 in place of 1 then you will get the last word.

What is the best way to extract the first word from a string in Python?

The easiest way to get the first word in string in python is to access the first element of the list which is returned by the string split() method. String split() method – The split() method splits the string into a list. The string is broken down using a specific character which is provided as an input parameter.

How can I get only the first word of a string in PHP?

Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string. This function is case-sensitive. . strstr ( $sentence , ' ' , true);


1 Answers

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.
}
like image 153
Laffen Avatar answered Sep 22 '22 08:09

Laffen