Function replacementSize [src]

Calculate the size needed in an output buffer to perform a replacement. The needle must not be empty.

Prototype

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

Parameters

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

Example

test replacementSize { try testing.expect(replacementSize(u8, "All your base are belong to us", "base", "Zig") == 29); try testing.expect(replacementSize(u8, "Favor reading code over writing code.", "code", "") == 29); try testing.expect(replacementSize(u8, "Only one obvious way to do things.", "things.", "things in Zig.") == 41); // Empty needle is not allowed but input may be empty. try testing.expect(replacementSize(u8, "", "x", "y") == 0); // Adjacent replacements. try testing.expect(replacementSize(u8, "\\n\\n", "\\n", "\n") == 2); try testing.expect(replacementSize(u8, "abbba", "b", "cd") == 8); }

Source

pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize { // Empty needle will loop forever. assert(needle.len > 0); var i: usize = 0; var size: usize = input.len; while (i < input.len) { if (mem.startsWith(T, input[i..], needle)) { size = size - needle.len + replacement.len; i += needle.len; } else { i += 1; } } return size; }