Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

split

zig

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");
like image 782
Stanislav Nikolov Avatar asked May 08 '26 00:05

Stanislav Nikolov


2 Answers

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://zig.guide/standard-library/iterators

like image 88
Stanislav Nikolov Avatar answered May 11 '26 14:05

Stanislav Nikolov


As of Nov 2024 std.mem.split is deprecated

You can instead use splitScalar

const std = @import("std");

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

There is also splitSequence, if you wish to split by a sequence, example:

var it = std.mem.splitSequence(u8, httpResponse, "\r\n")

like image 21
Cijin Cherian Avatar answered May 11 '26 15:05

Cijin Cherian