Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix String#sub with negative index #5491

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions spec/std/string_spec.cr
Expand Up @@ -1173,13 +1173,27 @@ describe "String" do
string.bytesize.should eq("あいのえお".bytesize)
end

it "subs at negative index with char" do
string = "abc".sub(-1, 'd')
string.should eq("abd")
string = string.sub(-2, 'n')
string.should eq("and")
end

it "subs at index with string" do
string = "hello".sub(1, "eee")
string.should eq("heeello")
string.bytesize.should eq(7)
string.size.should eq(7)
end

it "subs at negative index with string" do
string = "hello".sub(-1, "ooo")
string.should eq("hellooo")
string.bytesize.should eq(7)
string.size.should eq(7)
end

it "subs at index with string, non-ascii" do
string = "あいうえお".sub(2, "けくこ")
string.should eq("あいけくこえお")
Expand Down
2 changes: 1 addition & 1 deletion src/string.cr
Expand Up @@ -1857,7 +1857,7 @@ class String
end

private def sub_index(index, replacement)
index += size + 1 if index < 0
index += size if index < 0

byte_index = char_index_to_byte_index(index)
raise IndexError.new unless byte_index
Expand Down