ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Zig Simple String Concatenation with Manual Allocation

Zig

Goal -- WPM

Ready
Exercise Algorithm Area
1const std = @import("std");
2
3const Allocator = std.mem.Allocator;
4
5fn concatenateStrings(allocator: Allocator, str1: ?[]const u8, str2: ?[]const u8) ![]u8 {
6const len1 = str1.?.len catch 0;
7const len2 = str2.?.len catch 0;
8const total_len = len1 + len2;
9
10// Allocate memory for the concatenated string + null terminator
11const result = try allocator.alloc(total_len + 1, 1);
12
13// Copy the first string
14if (str1) |s1| {
15std.mem.copy(u8, result[0..len1], s1);
16}
17
18// Copy the second string
19if (str2) |s2| {
20std.mem.copy(u8, result[len1 .. len1 + len2], s2);
21}
22
23// Null-terminate the result
24result[total_len] = 0;
25
26return result;
27}
28
29pub fn main() !void {
30var gpa = std.heap.GeneralPurposeAllocator(.{}){};
31defer _ = gpa.deinit();
32const allocator = gpa.allocator();
33
34const s1 = "Hello, ";
35const s2 = "World!";
36
37const concatenated = try concatenateStrings(allocator, s1, s2);
38defer allocator.free(concatenated);
39
40std.debug.print("Concatenated string: {s}\n", .{concatenated});
41
42const empty_s1 = "";
43const concatenated_empty = try concatenateStrings(allocator, empty_s1, s2);
44defer allocator.free(concatenated_empty);
45std.debug.print("Concatenated with empty s1: {s}\n", .{concatenated_empty});
46
47const null_s2 = null;
48const concatenated_null = try concatenateStrings(allocator, s1, null_s2);
49defer allocator.free(concatenated_null);
50std.debug.print("Concatenated with null s2: {s}\n", .{concatenated_null});
51}
Algorithm description viewbox

Zig Simple String Concatenation with Manual Allocation

Algorithm description:

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-terminated. This is a fundamental operation for string manipulation and is often used when building dynamic strings or processing text data that requires dynamic resizing or combination.

Algorithm explanation:

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.

Pseudocode:

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 + null terminator
  result_buffer = allocator.alloc(total_length + 1)
  if allocation fails, return error

  // Copy string1
  if string1 is not null:
    copy string1 into result_buffer starting at index 0

  // Copy string2
  if string2 is not null:
    copy string2 into result_buffer starting at index length1

  // Add null terminator
  result_buffer[total_length] = 0

  return result_buffer