Function replace [src]

Replace needle with replacement as many times as possible, writing to an output buffer which is assumed to be of appropriate size. Use replacementSize to calculate an appropriate buffer size. The needle must not be empty. Returns the number of replacements made.

Prototype

pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize

Parameters

T: typeinput: []const Tneedle: []const Treplacement: []const Toutput: []T

Example

test replace { var output: [29]u8 = undefined; var replacements = replace(u8, "All your base are belong to us", "base", "Zig", output[0..]); var expected: []const u8 = "All your Zig are belong to us"; try testing.expect(replacements == 1); try testing.expectEqualStrings(expected, output[0..expected.len]); replacements = replace(u8, "Favor reading code over writing code.", "code", "", output[0..]); expected = "Favor reading over writing ."; try testing.expect(replacements == 2); try testing.expectEqualStrings(expected, output[0..expected.len]); // Empty needle is not allowed but input may be empty. replacements = replace(u8, "", "x", "y", output[0..0]); expected = ""; try testing.expect(replacements == 0); try testing.expectEqualStrings(expected, output[0..expected.len]); // Adjacent replacements. replacements = replace(u8, "\\n\\n", "\\n", "\n", output[0..]); expected = "\n\n"; try testing.expect(replacements == 2); try testing.expectEqualStrings(expected, output[0..expected.len]); replacements = replace(u8, "abbba", "b", "cd", output[0..]); expected = "acdcdcda"; try testing.expect(replacements == 3); try testing.expectEqualStrings(expected, output[0..expected.len]); }

Source

pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize { // Empty needle will loop until output buffer overflows. assert(needle.len > 0); var i: usize = 0; var slide: usize = 0; var replacements: usize = 0; while (slide < input.len) { if (mem.startsWith(T, input[slide..], needle)) { @memcpy(output[i..][0..replacement.len], replacement); i += replacement.len; slide += needle.len; replacements += 1; } else { output[i] = input[slide]; i += 1; slide += 1; } } return replacements; }