Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ If there are any issues with <b>complexity</b> please <b>open an issue</b>
| reverse | Reverses all the characters |
| split | Returns a slice based on delimiters |
| splitToString | Returns a String based on delimiters |
| lines | Returns a slice of Strings split by newlines |
| str | Returns the String as a slice |
| substr | Creates a string from a range |
| toLowercase | Converts (ASCII) characters to lowercase |
Expand Down
11 changes: 11 additions & 0 deletions zig-string-tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,17 @@ test "String Tests" {

try expectEqualStrings(newSplit.?.str(), "variable");

// lines
const lineSlice = "Line0\r\nLine1\nLine2";

var lineStr = try String.init_with_contents(arena.allocator(), lineSlice);
var linesSlice = try lineStr.lines();

try expectEqual(linesSlice.len, 3);
try expect(linesSlice[0].cmp("Line0"));
try expect(linesSlice[1].cmp("Line1"));
try expect(linesSlice[2].cmp("Line2"));

// toLowercase & toUppercase
myStr.toUppercase();
try expect(myStr.cmp("💯HELLO💯💯HELLO💯💯HELLO💯"));
Expand Down
18 changes: 18 additions & 0 deletions zig-string.zig
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,24 @@ pub const String = struct {
return null;
}

/// Splits the String into a slice of Strings by new line (\r\n or \n).
pub fn lines(self: *String) ![]String {
var lineArr = std.ArrayList(String).init(std.heap.page_allocator);
defer lineArr.deinit();

var selfClone = try self.clone();
defer selfClone.deinit();

_ = try selfClone.replace("\r\n", "\n");

var i: usize = 0;
while (try selfClone.splitToString("\n", i)) |line| : (i += 1) {
try lineArr.append(line);
}

return try lineArr.toOwnedSlice();
}

/// Clears the contents of the String but leaves the capacity
pub fn clear(self: *String) void {
if (self.buffer) |buffer| {
Expand Down