I’m iterating over text with iter = std.mem.splitSequence(u8, text, newline). I want to operate on each member of the sequence except the last. Is there a way to check if iter.next() == null without advancing the iterator?
I checked the implementation of splitSequence, and from there you can see that iter.index keeps track of where the next item starts. So if it is null, we’re already looking at the last item (i.e. iter.index being null implies that .next() is going to return null).
This code prints all but the last segment:
pub fn main() !void {
const data: []const u8 = "Hello, World!\nFoo Bar\nBaz";
var iter = std.mem.splitSequence(u8, data, "\n");
while (iter.next()) |line| {
if (iter.index == null) break;
std.debug.print("Line: {s}\n", .{line});
}
}
2 Likes
const std = @import("std");
pub fn main() !void {
// const text = "one";
const text = "one, two, three";
var it = std.mem.splitSequence(u8, text, ", ");
const last: ?[]const u8 = last: while (it.next()) |entry| {
if (it.peek() == null) break :last entry;
std.debug.print("entry: {s}\n", .{entry});
} else null;
std.debug.print("last entry: {s}\n", .{if (last) |l| l else "<null>"});
}
The SplitIterator doesn’t really produce zero element sequences, so last won’t be null in this example, but some other iterator might.
2 Likes
@trebe, I should have done this myself before asking! This solves my issue nicely – many thanks! ![]()
@Sze, food for thought – thanks!