Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get part of a string in swift?

Tags:

swift

I would like to find out how to get a part of a string in Swift. I am looking for the Swift equivalents of the Mid$, Right$, and Left$ functions. Any help would be appreciated.

like image 503
jlert Avatar asked Aug 13 '14 02:08

jlert


People also ask

How to find substring in Swift?

How to Find SubString in Swift? To find substring of a String in Swift, prepare Range object using start and end indices, then give this Range object to the string in square brackets as an index. The syntax to concatenate two strings is:

How do you create a string in Swift?

The syntax for string creation and manipulation is lightweight and readable, with a string literal syntax that’s similar to C. String concatenation is as simple as combining two strings with the + operator, and string mutability is managed by choosing between a constant or a variable, just like any other value in Swift.

What are string and character types in Swift?

Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.

How do you concatenate two strings in Swift?

Swift Substring. To find substring of a String in Swift, prepare range using start and end indexes, then use the range on the string. The syntax to concatenate two strings is: where startPosition and endPosition are integers that define the bounds of the substring in the main string str.


2 Answers

Swift 4, Swift5

Modern API has got this syntax:

let str = "Hello world!"
let prefix = String(str.prefix(1))
let suffix = String(str.suffix(1))
like image 131
Vyacheslav Avatar answered Nov 06 '22 21:11

Vyacheslav


Edit: This answer was from 2014 and is obsolete today, I recommend referencing Vyacheslav's answer instead

The equivalent of Left is substringToIndex

Example: (directly from this site)

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringToIndex(2))
//This grabs the first 2 digits of the string and stops there,
//which returns "AB"

The (rough) equivalent of Right is substringFromIndex

Example: (directly from the same site)

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringFromIndex(2))
//This jumps over the first 2 digits of the string and grabs the rest,
//which returns "CDEFGHI"

See https://web.archive.org/web/20170504165315/http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/

like image 34
Nick Meyer Avatar answered Nov 06 '22 21:11

Nick Meyer