Below is a simple string reversal algorithm implemented in Zig. This function takes a mutable slice of bytes ([]u8) as input and reverses it in place. Note that Zig strings are typically handled as arrays or slices of bytes, and we're assuming the input is mutable for this in-place reversal.
Explanation:
- The algorithm uses a loop to swap characters from the start and end of the string, moving towards the center.
- It only processes up to half the length of the string to avoid redundant swaps.
- If the string is empty or has one character, no swaps are needed.
Here's the code:
const std = @import("std");
pub fn reverseString(s: []u8) void {
const half_len = s.len / 2; // Calculate half the length
var i: usize = 0;
while (i < half_len) : (i += 1) {
const j = s.len - 1 - i; // Index from the end
const temp = s[i]; // Swap s[i] and s[j]
s[i] = s[j];
s[j] = temp;
}
}
// Example usage in a main function
pub fn main() !void {
var original: [5]u8 = [_]u8{'h', 'e', 'l', 'l', 'o'}; // Create a mutable array
reverseString(&original); // Pass a pointer to the array (as []u8)
// Print the reversed string
std.debug.print("Reversed: {s}\n", .{original});
}
How to Run:
- Save this code to a file, e.g.,
reverse.zig.
- Compile and run it using the Zig compiler:
zig build-exe reverse.zig
./reverse
Output: Reversed: olleh
Key Points:
- Input Type: The function expects
[]u8, which is a mutable slice. If you have an immutable string (e.g., a string literal like "hello", which is []const u8), you'll need to duplicate it first using an allocator or a buffer.
- Memory Handling: This implementation reverses the string in place, so it doesn't allocate new memory. If you need to work with immutable strings, you could modify it to return a new array (e.g., using
std.heap for allocation).
- Edge Cases:
- Empty string: No operations are performed.
- Single character: No operations are performed.
- Even/odd lengths: Handled correctly.
If you need a version that handles allocation or works with []const u8, let me know for further modifications!