I have not yet been able to figure out how to get a substring of a String
in Swift:
var str = “Hello, playground”
func test(str: String) -> String {
return str.substringWithRange( /* What goes here? */ )
}
test (str)
I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is what it suggests:
return str.substringWithRange(aRange: Range<String.Index>)
I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:
return str.substringWithRange(Range(0, 1))
And this:
let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)
return str.substringWithRange(r)
I've seen other answers (Finding index of character in Swift String) that seem to suggest that since String
is a bridge type for NSString
, the "old" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax):
let x = str.substringWithRange(NSMakeRange(0, 3))
Thoughts?
Sample Code for how to get substring in Swift 2.0
(i) Substring from starting index
Input:-
Output:-
(ii) Substring from particular index
Input:-
Output:-
I hope it will help you!
Easy solution with little code.
Make an extension that includes basic subStringing that nearly all other languages have:
Simply call this with
If you don't care about performance... this is probably the most concise solution in Swift 4
It enables you to do something like this:
For example to find the first name (up to the first space) in my full name:
start
andend
are of typeString.Index
here and are used to create aRange<String.Index>
and used in the subscript accessor (if a space is found at all in the original string).It's hard to create a
String.Index
directly from an integer position as used in the opening post. This is because in my name each character would be of equal size in bytes. But characters using special accents in other languages could have used several more bytes (depending on the encoding used). So what byte should the integer refer to?It's possible to create a new
String.Index
from an existing one using the methodssucc
andpred
which will make sure the correct number of bytes are skipped to get to the next code point in the encoding. However in this case it's easier to search for the index of the first space in the string to find the end index.Simple extension for
String
:SWIFT 2.0
simple:
SWIFT 3.0
SWIFT 4.0
Substring operations return an instance of the Substring type, instead of String.