Skip to content

Commit

Permalink
Merge pull request #42 from pedropark99/string
Browse files Browse the repository at this point in the history
Add small section to describe useful string functions
  • Loading branch information
pedropark99 authored Sep 18, 2024
2 parents b1569b9 + f4db65a commit d915aa8
Show file tree
Hide file tree
Showing 10 changed files with 206 additions and 10 deletions.
107 changes: 107 additions & 0 deletions Chapters/01-zig-weird.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,113 @@ got codepoint E382AB
```


### Some useful functions for strings

In this section, I just want to quickly describe some functions from the Zig Standard Library
that are very useful to use when working with strings. Most notably:

- `std.mem.eql()`: to compare if two strings are equal.
- `std.mem.splitScalar()`: to split a string into an array of substrings given a delimiter value.
- `std.mem.splitSequence()`: to split a string into an array of substrings given a substring delimiter.
- `std.mem.startsWith()`: to check if string starts with substring.
- `std.mem.endsWith()`: to check if string starts with substring.
- `std.mem.trim()`: to remove specific values from both start and end of the string.
- `std.mem.concat()`: to concatenate strings together.
- `std.mem.count()`: to count the occurrences of substring in the string.
- `std.mem.replace()`: to replace the occurrences of substring in the string.

Notice that all of these functions come from the `mem` module of
the Zig Standard Library. This module contains multiple functions and methods
that are useful to work with memory and sequences of bytes in general.

The `eql()` function is used to check if two arrays of data are equal or not.
Since strings are just arbitrary arrays of bytes, we can use this function to compare two strings together.
This function returns a boolean value indicating if the two strings are equal
or not. The first argument of this function is the data type of the elements of the arrays
that are being compared.

```{zig}
#| auto_main: true
#| build_type: "run"
const name: []const u8 = "Pedro";
try stdout.print(
"{any}\n", .{std.mem.eql(u8, name, "Pedro")}
);
```

The `splitScalar()` and `splitSequence()` functions are useful to split
a string into multiple fragments, like the `split()` method from Python strings. The difference between these two
methods is that the `splitScalar()` uses a single character as the separator to
split the string, while `splitSequence()` uses a sequence of characters (a.k.a. a substring)
as the separator. There is a practical example of these functions later in the book.

The `startsWith()` and `endsWith()` functions are pretty straightforward. They
return a boolean value indicating if the string (or, more precisely, if the array of data)
begins (`startsWith`) or ends (`endsWith`) with the sequence provided.

```{zig}
#| auto_main: true
#| build_type: "run"
const name: []const u8 = "Pedro";
try stdout.print(
"{any}\n", .{std.mem.startsWith(u8, name, "Pe")}
);
```

The `concat()` function, as the name suggests, concatenate two or more strings together.
Because the process of concatenating the strings involves allocating enough space to
accomodate all the strings together, this `concat()` function receives an allocator
object as input.

```{zig}
#| eval: false
#| auto_main: true
#| build_type: "run"
const str1 = "Hello";
const str2 = " you!";
const str3 = try std.mem.concat(
allocator, u8, &[_][]const u8{ str1, str2 }
);
try stdout.print("{s}\n", .{str3});
```

```
Hello you!
```

As you can imagine, the `replace()` function is used to replace substrings in a string by another substring.
This function works very similarly to the `replace()` method from Python strings. Therefore, you
provide a substring to search, and every time that the `replace()` function finds
this substring within the input string, it replaces this substring with the "replacement substring"
that you provided as input.

In the example below, we are taking the input string "Hello", and replacing all occurrences
of the substring "el" inside this input string with "34", and saving the results inside the
`buffer` object. As result, the `replace()` function returns an `usize` value that
indicates how many replacements were performed.


```{zig}
#| auto_main: true
#| build_type: "lib"
const str1 = "Hello";
var buffer: [5]u8 = undefined;
const nrep = std.mem.replace(
u8, str1, "el", "34", buffer[0..]
);
try stdout.print("New string: {s}\n", .{buffer});
try stdout.print("N of replacements: {d}\n", .{nrep});
```

```
New string: H34lo
N of replacements: 1
```






## Safety in Zig

Expand Down
6 changes: 6 additions & 0 deletions ZigExamples/zig-basics/comp-strings.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const std = @import("std");
const stdout = std.io.getStdOut().writer();
pub fn main() !void {
const name: []const u8 = "Pedro";
try stdout.print("{any}\n", .{std.mem.eql(u8, name, "Pedro")});
}
11 changes: 11 additions & 0 deletions ZigExamples/zig-basics/concat.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const std = @import("std");
const stdout = std.io.getStdOut().writer();

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const str1 = "Hello";
const str2 = " you!";
const str3 = try std.mem.concat(allocator, u8, &[_][]const u8{ str1, str2 });
try stdout.print("{s}\n", .{str3});
}
10 changes: 10 additions & 0 deletions ZigExamples/zig-basics/replace.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const std = @import("std");
const stdout = std.io.getStdOut().writer();

pub fn main() !void {
const str1 = "Hello";
var output: [5]u8 = undefined;
const nrep = std.mem.replace(u8, str1, "el", "34", output[0..]);
try stdout.print("New string: {s}\n", .{output});
try stdout.print("N of replacements: {d}\n", .{nrep});
}
4 changes: 2 additions & 2 deletions _freeze/Chapters/01-zig-weird/execute-results/html.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion _freeze/index/execute-results/html.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"hash": "87da007e8766ae15b718d8b3223b480f",
"result": {
"engine": "knitr",
"markdown": "---\nengine: knitr\nknitr: true\nsyntax-definition: \"./Assets/zig.xml\"\n---\n\n\n\n\n\n\n\n\n\n::: {.content-visible when-format=\"html\"}\n\n# Welcome {.unnumbered}\n\nWelcome! This is the initial page for the \"Open Access\" HTML version of the book \"Introduction to Zig: a project-based book\",\nwritten by [Pedro Duarte Faria](https://pedro-faria.netlify.app/).\nThis is an open book that provides an introduction to the [Zig programming language](https://ziglang.org/),\nwhich is a new general-purpose, and low-level language for building robust and optimal software.\n\n## About this book {.unnumbered}\n\nThis an open book, meaning that, it is open-source, and it will always be open\nfor anyone that wants to read it. However, this book is still under construction 🚧 and active development,\nso, it's contents might change drastically in the near future.\n\nAlso, this is a project-based book, which means that we learn how to use the Zig programming language\nthrough small and simple projects, in a similar style to the famous \"Python Crash Course\" book from Eric Matthes.\n\nOfficial book's repository: <https://github.com/pedropark99/zig-book>\n\n:::\n\n\n## About the author {.unnumbered}\n\nPedro Duarte Faria have a bachelor degree in Economics from Federal University of Ouro Preto - Brazil.\nCurrently, he is a Data Platform Engineer at [Blip](https://www.blip.ai/en/)[^blip], and\nan Associate Developer for Apache Spark 3.0 certified by Databricks.\n\n[^blip]: <https://www.blip.ai/en/>\n\n\nThe author have more than 4 years of experience in the data industry. Developing data products, pipelines,\nreports and analysis for research institutions and some of the largest companies in the\nbrazilian financial sector, such as the BMG Bank, Sodexo and Pan Bank.\n\nBut Pedro is also a passionate software developer that loves to\nlearn and teach about programming.\nAlthough Pedro uses many different languages in his work, he is specialized in the R programming language, and have given several\nlectures and courses about it, inside graduate centers (such as PPEA-UFOP^[<https://ppea.ufop.br/>]),\nin addition to federal and state organizations (such as FJP-MG^[<http://fjp.mg.gov.br/>]).\n\n\nPersonal Website: <https://pedro-faria.netlify.app/>\n\nLinkedin: <https://www.linkedin.com/in/pedro-faria-a68140209/>\n\nMastodon: [\\@pedropark99\\@fosstodon.org](https://fosstodon.org/@pedropark99)\n\nTwitter (X): [\\@PedroPark9](https://twitter.com/PedroPark9)\n\n## License {.unnumbered}\n\nCopyright © 2024 Pedro Duarte Faria. This book is licensed by the [CC-BY 4.0 Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/)[^cc-license].\n\n[^cc-license]: <https://creativecommons.org/licenses/by/4.0/>\n\n![](Figures/creative-commoms-88x31.png){width=88px}\n\n\n## Book compilation metadata {.unnumbered}\n\nThis book was compiled using the following versions of [Zig](https://ziglang.org) and [Quarto](https://quarto.org):\n\n\n\n\n\n- System version: Linux, 6.8.0-44-generic, NA, x86_64.\n\n- Zig version: 0.14.0-dev.1166+bb7050106.\n\n- Quarto version: 1.5.56.\n\n\n\n\n\n## Book citation {.unnumbered}\n\nYou can use the following BibTex entry to cite this book:\n\n```\n@book{pedro2024,\n author = {Pedro Duarte Faria},\n title = {Introduction to Zig},\n subtitle = {a project-based book},\n month = {December},\n edition = {1},\n year = {2024},\n address = {Belo Horizonte},\n url = {https://pedropark99.github.io/zig-book/}\n}\n```\n\n## Corresponding author and maintainer {.unnumbered}\n\nPedro Duarte Faria\n\nContact: [pedropark99\\@gmail.com](mailto:[email protected])\n\nPersonal website: <https://pedro-faria.netlify.app/>\n\n\n## Acknowledgments\n\nThis book is also a product of many conversations and exchanges that we had\nwith different people from the Zig community. I (Pedro Duarte Faria) am incredibly\ngrateful for these conversations, and also, for some direct contributions that we\nhad. Below we have a list of the people involved (name of the person with their usename in GitHub):\n\n\n\n\n\nCalin Martinconi (\\@martinconic), Steffen Roller (\\@sroller), Chris Boesch (\\@chrboesch), Lv Sihan (\\@Pokryton)\n",
"markdown": "---\nengine: knitr\nknitr: true\nsyntax-definition: \"./Assets/zig.xml\"\n---\n\n\n\n\n\n\n\n\n::: {.content-visible when-format=\"html\"}\n\n# Welcome {.unnumbered}\n\nWelcome! This is the initial page for the \"Open Access\" HTML version of the book \"Introduction to Zig: a project-based book\",\nwritten by [Pedro Duarte Faria](https://pedro-faria.netlify.app/).\nThis is an open book that provides an introduction to the [Zig programming language](https://ziglang.org/),\nwhich is a new general-purpose, and low-level language for building robust and optimal software.\n\n## About this book {.unnumbered}\n\nThis an open book, meaning that, it is open-source, and it will always be open\nfor anyone that wants to read it. However, this book is still under construction 🚧 and active development,\nso, it's contents might change drastically in the near future.\n\nAlso, this is a project-based book, which means that we learn how to use the Zig programming language\nthrough small and simple projects, in a similar style to the famous \"Python Crash Course\" book from Eric Matthes.\n\nOfficial book's repository: <https://github.com/pedropark99/zig-book>\n\n:::\n\n\n## About the author {.unnumbered}\n\nPedro Duarte Faria have a bachelor degree in Economics from Federal University of Ouro Preto - Brazil.\nCurrently, he is a Data Platform Engineer at [Blip](https://www.blip.ai/en/)[^blip], and\nan Associate Developer for Apache Spark 3.0 certified by Databricks.\n\n[^blip]: <https://www.blip.ai/en/>\n\n\nThe author have more than 4 years of experience in the data industry. Developing data products, pipelines,\nreports and analysis for research institutions and some of the largest companies in the\nbrazilian financial sector, such as the BMG Bank, Sodexo and Pan Bank.\n\nBut Pedro is also a passionate software developer that loves to\nlearn and teach about programming.\nAlthough Pedro uses many different languages in his work, he is specialized in the R programming language, and have given several\nlectures and courses about it, inside graduate centers (such as PPEA-UFOP^[<https://ppea.ufop.br/>]),\nin addition to federal and state organizations (such as FJP-MG^[<http://fjp.mg.gov.br/>]).\n\n\nPersonal Website: <https://pedro-faria.netlify.app/>\n\nLinkedin: <https://www.linkedin.com/in/pedro-faria-a68140209/>\n\nMastodon: [\\@pedropark99\\@fosstodon.org](https://fosstodon.org/@pedropark99)\n\nTwitter (X): [\\@PedroPark9](https://twitter.com/PedroPark9)\n\n## License {.unnumbered}\n\nCopyright © 2024 Pedro Duarte Faria. This book is licensed by the [CC-BY 4.0 Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/)[^cc-license].\n\n[^cc-license]: <https://creativecommons.org/licenses/by/4.0/>\n\n![](Figures/creative-commoms-88x31.png){width=88px}\n\n\n## Book compilation metadata {.unnumbered}\n\nThis book was compiled using the following versions of [Zig](https://ziglang.org) and [Quarto](https://quarto.org):\n\n\n\n\n- System version: Linux, 6.8.0-45-generic, NA, x86_64.\n\n- Zig version: 0.14.0-dev.1166+bb7050106.\n\n- Quarto version: 1.5.56.\n\n\n\n\n## Book citation {.unnumbered}\n\nYou can use the following BibTex entry to cite this book:\n\n```\n@book{pedro2024,\n author = {Pedro Duarte Faria},\n title = {Introduction to Zig},\n subtitle = {a project-based book},\n month = {December},\n edition = {1},\n year = {2024},\n address = {Belo Horizonte},\n url = {https://pedropark99.github.io/zig-book/}\n}\n```\n\n## Corresponding author and maintainer {.unnumbered}\n\nPedro Duarte Faria\n\nContact: [pedropark99\\@gmail.com](mailto:[email protected])\n\nPersonal website: <https://pedro-faria.netlify.app/>\n\n\n## Acknowledgments\n\nThis book is also a product of many conversations and exchanges that we had\nwith different people from the Zig community. I (Pedro Duarte Faria) am incredibly\ngrateful for these conversations, and also, for some direct contributions that we\nhad. Below we have a list of the people involved (name of the person with their usename in GitHub):\n\n\n\n\nCalin Martinconi (\\@martinconic), Steffen Roller (\\@sroller), Chris Boesch (\\@chrboesch), Lv Sihan (\\@Pokryton), saurabh sharma. (\\@esskayesss)\n",
"supporting": [],
"filters": [
"rmarkdown/pagebreak.lua"
Expand Down
1 change: 1 addition & 0 deletions contributors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ Calin Martinconi,@martinconic
Steffen Roller,@sroller
Chris Boesch,@chrboesch
Lv Sihan,@Pokryton
saurabh sharma.,@esskayesss
Loading

0 comments on commit d915aa8

Please sign in to comment.