SSteve SSteve - 2 years ago 79
Swift Question

What is the most succinct way to remove the first character from a string in Swift?

I want to delete the first character from a string. So far, the most succinct thing I've come up with is:

display.text = display.text!.substringFromIndex(advance(display.text!.startIndex, 1))

I know we can't index into a string with an
because of Unicode, but this solution seems awfully verbose. Is there another way that I'm overlooking?

Answer Source

I like the global dropFirst() function for this.

let original = "Hello" // Hello
let sliced = dropFirst(original) // ello

It's short, clear, and works for anything that conforms to the Sliceable protocol.

If you're using Swift 2, this answer has changed. You can still use dropFirst, but not without dropping the first character from your strings characters property and then converting the result back to a String. dropFirst has also become a method, not a function.

let original = "Hello" // Hello
let sliced = String(original.characters.dropFirst()) // ello

Another alternative is to use the suffix function to splice the string's UTF16View. Of course, this has to be converted back to a String afterwards as well.

let original = "Hello" // Hello
let sliced = String(suffix(original.utf16, original.utf16.count - 1)) // ello

All this is to say that the solution I originally provided has turned out not to be the most succinct way of doing this in newer versions of Swift. I recommend falling back on @chris' solution using removeAtIndex() if you're looking for a short and intuitive solution.

var original = "Hello" // Hello
let removedChar = original.removeAtIndex(original.startIndex)

original // ello

And as pointed out by @vacawama in the comments below, another option that doesn't modify the original String is to use substringFromIndex.

let original = "Hello" // Hello
let substring = original.substringFromIndex(advance(original.startIndex, 1)) // ello

Or if you happen to be looking to drop a character off the beginning and end of the String, you can use substringWithRange. Just be sure to guard against the condition when startIndex + n > endIndex - m.

let original = "Hello" // Hello

let newStartIndex = advance(original.startIndex, 1)
let newEndIndex = advance(original.endIndex, -1)

let substring = original.substringWithRange(newStartIndex..<newEndIndex) // ell

The last line can also be written using subscript notation.

let substring = original[newStartIndex..<newEndIndex]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download