Skip to content

Commit d915aa8

Browse files
authored
Merge pull request #42 from pedropark99/string
Add small section to describe useful string functions
2 parents b1569b9 + f4db65a commit d915aa8

File tree

10 files changed

+206
-10
lines changed

10 files changed

+206
-10
lines changed

Chapters/01-zig-weird.qmd

+107
Original file line numberDiff line numberDiff line change
@@ -1260,6 +1260,113 @@ got codepoint E382AB
12601260
```
12611261

12621262

1263+
### Some useful functions for strings
1264+
1265+
In this section, I just want to quickly describe some functions from the Zig Standard Library
1266+
that are very useful to use when working with strings. Most notably:
1267+
1268+
- `std.mem.eql()`: to compare if two strings are equal.
1269+
- `std.mem.splitScalar()`: to split a string into an array of substrings given a delimiter value.
1270+
- `std.mem.splitSequence()`: to split a string into an array of substrings given a substring delimiter.
1271+
- `std.mem.startsWith()`: to check if string starts with substring.
1272+
- `std.mem.endsWith()`: to check if string starts with substring.
1273+
- `std.mem.trim()`: to remove specific values from both start and end of the string.
1274+
- `std.mem.concat()`: to concatenate strings together.
1275+
- `std.mem.count()`: to count the occurrences of substring in the string.
1276+
- `std.mem.replace()`: to replace the occurrences of substring in the string.
1277+
1278+
Notice that all of these functions come from the `mem` module of
1279+
the Zig Standard Library. This module contains multiple functions and methods
1280+
that are useful to work with memory and sequences of bytes in general.
1281+
1282+
The `eql()` function is used to check if two arrays of data are equal or not.
1283+
Since strings are just arbitrary arrays of bytes, we can use this function to compare two strings together.
1284+
This function returns a boolean value indicating if the two strings are equal
1285+
or not. The first argument of this function is the data type of the elements of the arrays
1286+
that are being compared.
1287+
1288+
```{zig}
1289+
#| auto_main: true
1290+
#| build_type: "run"
1291+
const name: []const u8 = "Pedro";
1292+
try stdout.print(
1293+
"{any}\n", .{std.mem.eql(u8, name, "Pedro")}
1294+
);
1295+
```
1296+
1297+
The `splitScalar()` and `splitSequence()` functions are useful to split
1298+
a string into multiple fragments, like the `split()` method from Python strings. The difference between these two
1299+
methods is that the `splitScalar()` uses a single character as the separator to
1300+
split the string, while `splitSequence()` uses a sequence of characters (a.k.a. a substring)
1301+
as the separator. There is a practical example of these functions later in the book.
1302+
1303+
The `startsWith()` and `endsWith()` functions are pretty straightforward. They
1304+
return a boolean value indicating if the string (or, more precisely, if the array of data)
1305+
begins (`startsWith`) or ends (`endsWith`) with the sequence provided.
1306+
1307+
```{zig}
1308+
#| auto_main: true
1309+
#| build_type: "run"
1310+
const name: []const u8 = "Pedro";
1311+
try stdout.print(
1312+
"{any}\n", .{std.mem.startsWith(u8, name, "Pe")}
1313+
);
1314+
```
1315+
1316+
The `concat()` function, as the name suggests, concatenate two or more strings together.
1317+
Because the process of concatenating the strings involves allocating enough space to
1318+
accomodate all the strings together, this `concat()` function receives an allocator
1319+
object as input.
1320+
1321+
```{zig}
1322+
#| eval: false
1323+
#| auto_main: true
1324+
#| build_type: "run"
1325+
const str1 = "Hello";
1326+
const str2 = " you!";
1327+
const str3 = try std.mem.concat(
1328+
allocator, u8, &[_][]const u8{ str1, str2 }
1329+
);
1330+
try stdout.print("{s}\n", .{str3});
1331+
```
1332+
1333+
```
1334+
Hello you!
1335+
```
1336+
1337+
As you can imagine, the `replace()` function is used to replace substrings in a string by another substring.
1338+
This function works very similarly to the `replace()` method from Python strings. Therefore, you
1339+
provide a substring to search, and every time that the `replace()` function finds
1340+
this substring within the input string, it replaces this substring with the "replacement substring"
1341+
that you provided as input.
1342+
1343+
In the example below, we are taking the input string "Hello", and replacing all occurrences
1344+
of the substring "el" inside this input string with "34", and saving the results inside the
1345+
`buffer` object. As result, the `replace()` function returns an `usize` value that
1346+
indicates how many replacements were performed.
1347+
1348+
1349+
```{zig}
1350+
#| auto_main: true
1351+
#| build_type: "lib"
1352+
const str1 = "Hello";
1353+
var buffer: [5]u8 = undefined;
1354+
const nrep = std.mem.replace(
1355+
u8, str1, "el", "34", buffer[0..]
1356+
);
1357+
try stdout.print("New string: {s}\n", .{buffer});
1358+
try stdout.print("N of replacements: {d}\n", .{nrep});
1359+
```
1360+
1361+
```
1362+
New string: H34lo
1363+
N of replacements: 1
1364+
```
1365+
1366+
1367+
1368+
1369+
12631370

12641371
## Safety in Zig
12651372

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const std = @import("std");
2+
const stdout = std.io.getStdOut().writer();
3+
pub fn main() !void {
4+
const name: []const u8 = "Pedro";
5+
try stdout.print("{any}\n", .{std.mem.eql(u8, name, "Pedro")});
6+
}

ZigExamples/zig-basics/concat.zig

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const std = @import("std");
2+
const stdout = std.io.getStdOut().writer();
3+
4+
pub fn main() !void {
5+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
6+
const allocator = gpa.allocator();
7+
const str1 = "Hello";
8+
const str2 = " you!";
9+
const str3 = try std.mem.concat(allocator, u8, &[_][]const u8{ str1, str2 });
10+
try stdout.print("{s}\n", .{str3});
11+
}

ZigExamples/zig-basics/replace.zig

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const std = @import("std");
2+
const stdout = std.io.getStdOut().writer();
3+
4+
pub fn main() !void {
5+
const str1 = "Hello";
6+
var output: [5]u8 = undefined;
7+
const nrep = std.mem.replace(u8, str1, "el", "34", output[0..]);
8+
try stdout.print("New string: {s}\n", .{output});
9+
try stdout.print("N of replacements: {d}\n", .{nrep});
10+
}

_freeze/Chapters/01-zig-weird/execute-results/html.json

+2-2
Large diffs are not rendered by default.

_freeze/index/execute-results/html.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"hash": "87da007e8766ae15b718d8b3223b480f",
33
"result": {
44
"engine": "knitr",
5-
"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",
5+
"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",
66
"supporting": [],
77
"filters": [
88
"rmarkdown/pagebreak.lua"

contributors.txt

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ Calin Martinconi,@martinconic
33
Steffen Roller,@sroller
44
Chris Boesch,@chrboesch
55
Lv Sihan,@Pokryton
6+
saurabh sharma.,@esskayesss

0 commit comments

Comments
 (0)