splitzig

How do I split a string in zig by a specific character?


I have a simple sentence in a string. I want to print each word on a new line or otherwise just do some calculation on each word?

Is there something similar to python's "Hello World".split() in zig? Something like this:

var arr = std.strings.split("Hello world");

Solution

  • Here is the simplest way I found

    const std = @import("std");
    
    pub fn main() !void {
        var it = std.mem.split(u8, "Hello World", " ");
        while (it.next()) |x| {
            std.debug.print("{s}\n", .{x});
        }
    }
    

    It looks like splitting is implemented in the standard mem module. .split returns SplitIterator which is a structure with a .next() method. When .next() returns null, the while stops. This is a common pattern in zig:

    https://ziglearn.org/chapter-2/#iterators