Skip to content

Commit

Permalink
Added splitToString
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubSzark committed Jan 26, 2021
1 parent 60ef4e1 commit 21a18ea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
7 changes: 7 additions & 0 deletions zig-string-tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,13 @@ test "String Tests" {
assert(eql(u8, splitStr.split("=", 0).?, "variable"));
assert(eql(u8, splitStr.split("=", 1).?, "'value'"));

// splitToString
var newSplit = try splitStr.splitToString("=", 0);
assert(newSplit != null);
defer newSplit.?.deinit();

assert(eql(u8, newSplit.?.str(), "variable"));

// toLowercase & toUppercase
myStr.toUppercase();
assert(myStr.cmp("💯HELLO💯💯HELLO💯💯HELLO💯"));
Expand Down
18 changes: 15 additions & 3 deletions zig-string.zig
Original file line number Diff line number Diff line change
Expand Up @@ -289,16 +289,16 @@ pub const String = struct {
}

/// Splits the String into a slice, based on a delimiter and an index
pub fn split(self: String, delimiter: []const u8, index: usize) ?[]const u8 {
pub fn split(self: *const String, delimiters: []const u8, index: usize) ?[]const u8 {
if (self.buffer) |buffer| {
var i: usize = 0;
var block: usize = 0;
var start: usize = 0;

while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (size == delimiter.len) {
if (std.mem.eql(u8, delimiter, buffer[i..(i + size)])) {
if (size == delimiters.len) {
if (std.mem.eql(u8, delimiters, buffer[i..(i + size)])) {
if (block == index) return buffer[start..i];
start = i + size;
block += 1;
Expand All @@ -316,6 +316,18 @@ pub const String = struct {
return null;
}

/// Splits the String into a new string, based on delimiters and an index
/// The user of this function is in charge of the memory of the new String.
pub fn splitToString(self: *const String, delimiters: []const u8, index: usize) Error!?String {
if (self.split(delimiters, index)) |block| {
var string = String.init(self.allocator);
try string.concat(block);
return string;
}

return null;
}

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

0 comments on commit 21a18ea

Please sign in to comment.