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");
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With