Zig Simple String Concatenation with Manual Allocation
const std = @import("std"); const Allocator = std.mem.Allocator; fn concatenateStrings(allocator: Allocator, str1: ?[]const u8, str2: ?[]const u8) ![]u8 { const len1 = str1.?.len catch 0; const len2 = str2.?.len catch 0; const total_len = len1 + len2; // Allocate memory for the c...
This Zig code provides a function `concatenateStrings` that merges two optional string slices into a single, newly allocated string. It uses a provided `Allocator` to manage memory for the result, ensuring it's null-term...
The `concatenateStrings` function takes an `Allocator` and two optional string slices (`?[]const u8`). It first determines the lengths of the input strings, treating null pointers as empty strings (length 0). It then allocates enough memory from the provided `allocator` to hold both strings plus a null terminator (`\0`). The contents of the input strings are copied into the newly allocated buffer using `std.mem.copy`. Finally, a null terminator is placed at the end of the buffer, and the resulting slice is returned. The `main` function demonstrates its usage with a `GeneralPurposeAllocator`, including handling optional inputs and freeing the allocated memory. The time complexity is O(N+M) where N and M are the lengths of the input strings, due to copying. Space complexity is O(N+M) for the new string.
function concatenateStrings(allocator, string1, string2): length1 = length of string1, or 0 if null/empty length2 = length of string2, or 0 if null/empty total_length = length1 + length2 // Allocate memory for the result...