Hello everyone,
I am new to the zig language and trying toy exercises like string_sorting etc.
I would like to get my below code reviewed, please feel free to let me know any and every improvement I can make to it.
const std = @import("std");
pub fn main() void {
const str = "cbawdd";
std.debug.print("unsorted: {s}\n", .{str});
const sort_str = sort_string(str);
std.debug.print("sorted: {s}\n", .{sort_str});
}
fn sort_string(ss: []const u8) [6]u8 {
// Function to sort the given 6 characters string.
// in an ascending order.
// Make the immutable string into mutable string
// so that it can be manipulated.
var buf: [6]u8 = undefined;
for (0..ss.len) |i| {
buf[i] = ss[i];
}
// sort the string
for (0..buf.len) |i| {
for (0..i) |k| {
const j = i - k;
if (buf[j] < buf[j - 1]) {
const tmp = buf[j];
buf[j] = buf[j - 1];
buf[j - 1] = tmp;
}
}
}
return buf;
}
I do have a few questions:
- The above only works for six character strings, how can I make it to work with a string of any length?
- In the
sort_stringfunction I have to first make[]const u8to a mutable[6]u8type and to do so I read we can use allocator too, which method is better the above for loop or the allocator one? - As the
strconst is a pointer to the actual bytescbawdd, I would like to edit the actual string using the pointer instead of storing it in a new const (sort_str), how can I do so?
Please let me know your thoughts.
Cheers,
DD.