0

How do I substring a string in swift 4.

I would like to convert:

"Hello, World!"

Into:

"Hello"

0

1 Answer 1

-3

Swift has no built in function to make this easy so I wrote a simple extension to get the same functionality as other languages such as python which have really easy substring functions.

Extension

Outside your class, add this extension for strings.

extension String { func substring(start: Int, range: Int) -> String { let characterArray = Array(self) var tempArray:[Character] = [] let starting = start let ending = start + range for i in (starting...ending) { tempArray.append(characterArray[i]) } let finalString = String(tempArray) return finalString } } 

Usage

let myString = "Hello, World!" print(myString.substring(start: 0, range: 4)) 

This prints:

"Hello"

How It Works

The extension works by turning the string into an array of separate characters then creates a loop which appends the desired characters into a new string which is determined by the function's parameters.

Thanks for stopping by. I hope apple add this basic functionality to their language soon! The above code is a bit messy so if anyone wants to clean it up then feel free!

Sign up to request clarification or add additional context in comments.

6 Comments

Who told you that it hasn't ??
Well, no basic substring function such as python has. I thought this would be useful for beginners such as myself
If your range is 4 you should get Hell not Hello
Btw naming range the length is misleading
Have a look at the various answers to stackoverflow.com/q/39677330/1187415 (of which your question is a duplicate) or stackoverflow.com/q/24092884/1187415 for more efficient solutions.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.