Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to succinctly get the first 5 characters of a string in swift?

Tags:

swift

What is the most succinct way to get the first 5 characters of a String in swift? Thank you.

like image 253
user1615898 Avatar asked Mar 25 '17 04:03

user1615898


People also ask

How do I retrieve the first 5 characters from a string?

string str = yourStringVariable. Substring(0,5);

How do you find the first few letters of a string?

To get the first N characters of a string, we can also call the substring() method on the string, passing 0 and N as the first and second arguments respectively. For example, str. substring(0, 3) returns a new string containing the first 3 characters of str .

How do I find the first character of a string in Swift?

To get the first character from a string, we can use the string. first property in swift.

How do I remove the first 3 characters of a string in Swift?

To remove the first character from a string , we can use the built-in removeFirst() method in Swift.


2 Answers

First 5 chars

let str = "SampleText"
let result = String(str.characters.prefix(5)) // result = "Sampl"

SWIFT 4

let str = "SampleText"
let result = String(str.prefix(5)) // result = "Sampl"
like image 174
Ganesh Manickam Avatar answered Oct 13 '22 06:10

Ganesh Manickam


In Swift 4 it changed:

let text         = "sampleText"

let resultPrefix = text.prefix(5)  //result = "sampl"
let resultSuffix = text.suffix(6) // result = "eText"
like image 35
Yigit Yilmaz Avatar answered Oct 13 '22 07:10

Yigit Yilmaz