What Is the Easiest Way to Remove the First Character from a String

What is the easiest way to remove the first character from a string?

I kind of favor using something like:


asdf = "[12,23,987,43"
asdf[0] = ''

p asdf
# >> "12,23,987,43"

I'm always looking for the fastest and most readable way of doing things:

require 'benchmark'

N = 1_000_000

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }

end

Running on my Mac Pro:

1.9.3
user system total real
[0] 0.840000 0.000000 0.840000 ( 0.847496)
sub 1.960000 0.010000 1.970000 ( 1.962767)
gsub 4.350000 0.020000 4.370000 ( 4.372801)
[1..-1] 0.710000 0.000000 0.710000 ( 0.713366)
slice 1.020000 0.000000 1.020000 ( 1.020336)
length 1.160000 0.000000 1.160000 ( 1.157882)

Updating to incorporate one more suggested answer:

require 'benchmark'

N = 1_000_000

class String
def eat!(how_many = 1)
self.replace self[how_many..-1]
end

def first(how_many = 1)
self[0...how_many]
end

def shift(how_many = 1)
shifted = first(how_many)
self.replace self[how_many..-1]
shifted
end
alias_method :shift!, :shift
end

class Array
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
b.report('eat!') { N.times { "[12,23,987,43".eat! } }
b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

2.1.2
user system total real
[0] 0.300000 0.000000 0.300000 ( 0.295054)
sub 0.630000 0.000000 0.630000 ( 0.631870)
gsub 2.090000 0.000000 2.090000 ( 2.094368)
[1..-1] 0.230000 0.010000 0.240000 ( 0.232846)
slice 0.320000 0.000000 0.320000 ( 0.320714)
length 0.340000 0.000000 0.340000 ( 0.341918)
eat! 0.460000 0.000000 0.460000 ( 0.452724)
reverse 0.400000 0.000000 0.400000 ( 0.399465)

And another using /^./ to find the first character:

require 'benchmark'

N = 1_000_000

class String
def eat!(how_many = 1)
self.replace self[how_many..-1]
end

def first(how_many = 1)
self[0...how_many]
end

def shift(how_many = 1)
shifted = first(how_many)
self.replace self[how_many..-1]
shifted
end
alias_method :shift!, :shift
end

class Array
def eat!(how_many = 1)
self.replace self[how_many..-1]
end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
b.report('[/^./]') { N.times { "[12,23,987,43"[/^./] = '' } }
b.report('[/^\[/]') { N.times { "[12,23,987,43"[/^\[/] = '' } }
b.report('sub+') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }
b.report('sub') { N.times { "[12,23,987,43".sub(/^\[/, "") } }
b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
b.report('eat!') { N.times { "[12,23,987,43".eat! } }
b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

# >> 2.1.5
# >> user system total real
# >> [0] 0.270000 0.000000 0.270000 ( 0.270165)
# >> [/^./] 0.430000 0.000000 0.430000 ( 0.432417)
# >> [/^\[/] 0.460000 0.000000 0.460000 ( 0.458221)
# >> sub+ 0.590000 0.000000 0.590000 ( 0.590284)
# >> sub 0.590000 0.000000 0.590000 ( 0.596366)
# >> gsub 1.880000 0.010000 1.890000 ( 1.885892)
# >> [1..-1] 0.230000 0.000000 0.230000 ( 0.223045)
# >> slice 0.300000 0.000000 0.300000 ( 0.299175)
# >> length 0.320000 0.000000 0.320000 ( 0.325841)
# >> eat! 0.410000 0.000000 0.410000 ( 0.409306)
# >> reverse 0.390000 0.000000 0.390000 ( 0.393044)

Here's another update on faster hardware and a newer version of Ruby:

2.3.1
user system total real
[0] 0.200000 0.000000 0.200000 ( 0.204307)
[/^./] 0.390000 0.000000 0.390000 ( 0.387527)
[/^\[/] 0.360000 0.000000 0.360000 ( 0.360400)
sub+ 0.490000 0.000000 0.490000 ( 0.492083)
sub 0.480000 0.000000 0.480000 ( 0.487862)
gsub 1.990000 0.000000 1.990000 ( 1.988716)
[1..-1] 0.180000 0.000000 0.180000 ( 0.181673)
slice 0.260000 0.000000 0.260000 ( 0.266371)
length 0.270000 0.000000 0.270000 ( 0.267651)
eat! 0.400000 0.010000 0.410000 ( 0.398093)
reverse 0.340000 0.000000 0.340000 ( 0.344077)

Why is gsub so slow?

After doing a search/replace, gsub has to check for possible additional matches before it can tell if it's finished. sub only does one and finishes. Consider gsub like it's a minimum of two sub calls.

Also, it's important to remember that gsub, and sub can also be handicapped by poorly written regex which match much more slowly than a sub-string search. If possible anchor the regex to get the most speed from it. There are answers here on Stack Overflow demonstrating that so search around if you want more information.

R remove first character from string

If we need to remove the first character, use sub, match one character (. represents a single character), replace it with ''.

sub('.', '', listfruit)
#[1] "applea" "bananab" "ranggeo"

Or for the first and last character, match the character at the start of the string (^.) or the end of the string (.$) and replace it with ''.

gsub('^.|.$', '', listfruit)
#[1] "apple" "banana" "rangge"

We can also capture it as a group and replace with the backreference.

sub('^.(.*).$', '\\1', listfruit)
#[1] "apple" "banana" "rangge"

Another option is with substr

substr(listfruit, 2, nchar(listfruit)-1)
#[1] "apple" "banana" "rangge"

How do you remove the first character of a string?

Assuming that the question uses "character" to refer to what Go calls a rune, then use utf8.DecodeRuneInString to get the size of the first rune and then slice:

func trimFirstRune(s string) string {
_, i := utf8.DecodeRuneInString(s)
return s[i:]
}

playground example

As peterSO demonstrates in the playground example linked from his comment, range on a string can also be used to find where the first rune ends:

func trimFirstRune(s string) string {
for i := range s {
if i > 0 {
// The value i is the index in s of the second
// rune. Slice to remove the first rune.
return s[i:]
}
}
// There are 0 or 1 runes in the string.
return ""
}

Remove First Character of (Original) String in JavaScript

Use substring

let str = "stake";str = str.substring(1);console.log(str);

Fastest way to remove first char in a String

The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".

The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable.

(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.)

I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.

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

If you're using Swift 3, you can ignore the second section of this answer. Good news is, this is now actually succinct again! Just using String's new remove(at:) method.

var myString = "Hello, World"
myString.remove(at: myString.startIndex)

myString // "ello, World"

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]

Delete first character of string if it is 0

You can remove the first character of a string using substring:

var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"

To remove all 0's at the start of the string:

var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}

How to remove the first and the last character of a string

Here you go