strinc.rb (sub, gsub): use byte index instead of char index.

This commit is contained in:
Yukihiro "Matz" Matsumoto
2022-05-17 18:20:06 +09:00
parent ce141b1332
commit 038aa6beb2
2 changed files with 11 additions and 11 deletions
+7 -7
View File
@@ -60,8 +60,8 @@ class String
end
offset = 0
result = []
while found = index(pattern, offset)
result << self[offset, found - offset]
while found = self.byteindex(pattern, offset)
result << self.byteslice(offset, found - offset)
offset = found + plen
result << if block
block.call(pattern).to_s
@@ -69,11 +69,11 @@ class String
self.__sub_replace(replace, pattern, found)
end
if plen == 0
result << self[offset, 1]
result << self.byteslice(offset, 1)
offset += 1
end
end
result << self[offset..-1] if offset < length
result << self.byteslice(offset..-1) if offset < length
result.join
end
@@ -119,16 +119,16 @@ class String
block = nil
end
result = []
found = index(pattern)
found = self.index(pattern)
return self.dup unless found
result << self[0, found]
result << self.byteslice(0, found)
offset = found + pattern.length
result << if block
block.call(pattern).to_s
else
self.__sub_replace(replace, pattern, found)
end
result << self[offset..-1] if offset < length
result << self.byteslice(offset..-1) if offset < length
result.join
end
+4 -4
View File
@@ -2831,8 +2831,8 @@ mrb_str_setbyte(mrb_state *mrb, mrb_value str)
/*
* call-seq:
* str.byteslice(integer) -> new_str or nil
* str.byteslice(integer, integer) -> new_str or nil
* str.byteslice(range) -> new_str or nil
* str.byteslice(integer, integer) -> new_str or nil
* str.byteslice(range) -> new_str or nil
*
* Byte Reference---If passed a single Integer, returns a
* substring of one byte at that position. If passed two Integer
@@ -2910,13 +2910,13 @@ sub_replace(mrb_state *mrb, mrb_value self)
mrb_str_cat(mrb, result, "\\", 1);
break;
case '`':
mrb_str_cat(mrb, result, RSTRING_PTR(self), chars2bytes(self, 0, found));
mrb_str_cat(mrb, result, RSTRING_PTR(self), found);
break;
case '&': case '0':
mrb_str_cat(mrb, result, match, mlen);
break;
case '\'':
offset = chars2bytes(self, 0, found) + mlen;
offset = found + mlen;
if (RSTRING_LEN(self) > offset) {
mrb_str_cat(mrb, result, RSTRING_PTR(self)+offset, RSTRING_LEN(self)-offset);
}