Dropping first and last
One way to remove both the first and last letters of a string can be done by nesting the NSString
methods substringToIndex:
and substringFromIndex:
:
NSString *helloString = @"Hello";
NSString *butFirstAndLast = [[helloString substringToIndex:helloString.length - 1] substringFromIndex:1];
NSLog(@"%@", butFirstAndLast); // "ell"
Or we can do this by by making an NSRange
of everything but the first and last letters, and using the NSString
substringWithRange:
method:
NSString *helloString = @"Hello";
NSRange endsRange = NSMakeRange(1, helloString.length - 2);
NSString *butFirstAndLast = [helloString substringWithRange:endsRange];
NSLog(@"%@", butFirstAndLast); // "ell"
In Swift, if we have a mutable String
, we can remove the first and last letters with removeAtIndex
:
var helloString = "Hello"
let start = helloString.startIndex
helloString.removeAtIndex(start)
println(helloString) // "ello"
let end = helloString.endIndex.predecessor()
helloString.removeAtIndex(end)
println(helloString) // "ell"
Or we can use String
subscripting, using a Range
with the startIndex.successor()
and endIndex.predecessor()
:
var helloString = "Hello"
let endsRange = Range(start: helloString.startIndex.successor(),
end: helloString.endIndex.predecessor())
let butFirstAndLast = helloString[endsRange]
println(butFirstAndLast) // "ell"
The Swift standard library also has the dropFirst
and dropLast
functions. These take a type that conforms to the Sliceable
protocol and return a new slice that contains everything but the first or last element.
So this could be used to drop the first and/or last elements of an Array
:
let arrayOfInts = [0, 1, 2, 3, 4, 5, 6]
let butFirst = dropFirst(arrayOfInts)
println(butFirst) // "[1, 2, 3, 4, 5, 6]"
let butLast = dropLast(arrayOfInts)
println(butLast) // "[0, 1, 2, 3, 4, 5]"
// Nest the functions together to drop both elements.
let butFirstAndLast = dropFirst(dropLast(arrayOfInts))
println(butFirstAndLast) // "[1, 2, 3, 4, 5]"
And to drop the first and/or last letters of a String
:
let helloString = "Hello"
let butFirst = dropFirst(helloString)
println(butFirst) // "ello"
let butLast = dropLast(helloString)
println(butLast) // "Hell"
// Nest the functions together to drop both letters.
let butFirstAndLast = dropFirst(dropLast(helloString))
println(butFirstAndLast) // "ell"