Сравнение и поиск байтов
Используйте вспомогательные функции std.mem для строк.
«Сравнение и поиск байтов» — бесплатный урок Zig Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
You Cannot Use ==
Two slices are different windows, so == compares pointers and lengths, not contents. Comparing text needs a real byte-by-byte check.
std.mem to the Rescue
The standard library module std.mem works on slices of any element type, and that includes your []const u8 strings.
const std = @import("std");
const mem = std.mem;eql Compares Contents
Use mem.eql to test whether two slices hold the same bytes in the same order. It returns a plain bool you can branch on.
mem.eql(u8, "zig", "zig"); // truePass the Element Type
Many std.mem helpers take the element type as their first argument. For strings that argument is always u8, matching []const u8.
Find a Substring
Search for text inside text with indexOf. It returns an optional index: the position of the first match, or null if absent.
mem.indexOf(u8, "hello", "ll"); // 2Handle the null
Because indexOf returns an optional, unwrap it with if or orelse. A null result simply means the needle was not found.
if (mem.indexOf(u8, h, n)) |i| {
// found at i
}Search from the End
Need the last occurrence instead of the first? Reach for lastIndexOf, which scans backward and returns an optional index too.
Prefix and Suffix
Check how a string begins or ends with startsWith and endsWith. Both take u8 and return a clean bool, perfect for parsing.
mem.startsWith(u8, "main.zig", "main");Single-Byte Search
To locate one byte rather than a substring, use indexOfScalar. It is the fast path when you only need a single character.
mem.indexOfScalar(u8, "a,b", ',');Count Occurrences
Use mem.count to tally how many times a needle appears in the text. It returns a usize, never null, even when the count is zero.
mem.count(u8, "aaa", "a"); // 3Case Sensitivity
These helpers are case-sensitive: A and a are different bytes. Normalize case first if you want a case-insensitive match.
Quick Check
You want to know if two strings contain exactly the same text.
Recap
You compared text with mem.eql and searched it using indexOf, startsWith, indexOfScalar, and count, all aware of null and case. 🔍
Часто задаваемые вопросы
Урок «Сравнение и поиск байтов» бесплатный?
Да — полный текст урока «Сравнение и поиск байтов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Сравнение и поиск байтов»?
Используйте вспомогательные функции std.mem для строк. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Сравнение и поиск байтов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Строки — это []const u8
- Строковые литералы и экранирование
- Сравнение и поиск байтов
- Форматирование текста с помощью std.fmt