Zig Tutorial #2

Robert Guiscard
2 min readMar 9, 2021

--

In this tutorial, I tried to manipulate the string in Zig. First, we can use this zig-string library. While there is no official package manager for Zig, you can follow this method to add packages: https://ziglearn.org/chapter-3/#packages

I have a file format which looks like this:

> Comment
MFVFLVLLPLVSSQCVNLTTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS
NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASTEKSNIIRGWIFGTTLDSKTQSLLIV

I would like to format it into every 10 characters per span like this:

> Comment is not touched
MFVFLVLLPL VSSQCVNLTT RTQLPPAYTN SFTRGVYYPD KVFRSSVLHS TQDLFLPFFS
NVTWFHAIHV SGTNGTKRFD NPVLPFNDGV YFASTEKSNI IRGWIFGTTL DSKTQSLLIV

It is easier to find the character at certain position. Here is the codes to do so:

const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const String = @import("zig-string").String;pub fn main() anyerror!void {
const fname = "spike.fasta";
var f = try fs.cwd().openFile(fname, fs.File.OpenFlags{ .read = true});
defer f.close();
const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var input = String.init(allocator);
defer input.deinit();
var output = String.init(allocator);
defer output.deinit();
while (true) {
if (f.reader().readUntilDelimiterAlloc(allocator, '\n', 1024)) |c| {
if(mem.eql(u8, c[0..1], ">")) { // <-- could be out of bound
try stdout.print("{}\n", .{c})
} else {
try input.concat(c);
while (input.len() > 10) {
var substr = try input.substr(0, 10);
defer substr.deinit();
try output.concat(substr.str());
try output.concat(" ");
if (output.len() > 60) {
try stdout.print("{} **\n", .{output.str()});
output.clear();
}
try input.removeRange(0, 10);
}
}
} else |err| {
try stdout.print("{}", .{output.str()});
try stdout.print("{} **\n", .{input.str()});
try stdout.print("== {} ==\n", .{err});
break;
}
}
}

mem.eql is used to check the first character per line is > or not. This part could cause error if the line is empty. It then output the line for every 10 characters. It is not a very efficient way to do so, but it works for now.

Zig is still short of many convenient functions. It will takes time to be mature.

--

--

No responses yet