Como Converter Maiúsculas e Minúsculas em Zig

Como Converter Maiúsculas e Minúsculas em Zig

A conversão entre maiúsculas e minúsculas é essencial para normalização de texto, comparações case-insensitive e formatação. Zig fornece funções no módulo std.ascii para trabalhar com caracteres ASCII.

Converter Caractere Individual

As funções std.ascii.toLower e std.ascii.toUpper convertem um caractere por vez.

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    // Converter caractere para minúscula
    const maiusculo: u8 = 'A';
    const minusculo = std.ascii.toLower(maiusculo);
    try stdout.print("'{c}' -> '{c}'\n", .{ maiusculo, minusculo });

    // Converter caractere para maiúscula
    const lower: u8 = 'z';
    const upper = std.ascii.toUpper(lower);
    try stdout.print("'{c}' -> '{c}'\n", .{ lower, upper });

    // Caracteres não-alfabéticos não são alterados
    const digito: u8 = '5';
    try stdout.print("'{c}' -> toLower: '{c}', toUpper: '{c}'\n", .{
        digito,
        std.ascii.toLower(digito),
        std.ascii.toUpper(digito),
    });
}

Saída esperada:

'A' -> 'a'
'z' -> 'Z'
'5' -> toLower: '5', toUpper: '5'

Converter String Completa para Minúsculas

Use std.ascii.lowerString para converter uma string inteira para minúsculas em um buffer fixo.

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    // Converter para minúsculas em buffer fixo
    const texto = "OLÁ MUNDO ZIG";
    var buf: [64]u8 = undefined;
    const resultado = std.ascii.lowerString(buf[0..texto.len], texto);
    try stdout.print("Original:   \"{s}\"\n", .{texto});
    try stdout.print("Minúsculas: \"{s}\"\n", .{resultado});
}

Saída esperada:

Original:   "OLÁ MUNDO ZIG"
Minúsculas: "olÁ mundo zig"

Nota: As funções de std.ascii trabalham apenas com caracteres ASCII (0-127). Caracteres acentuados como “Á” não são convertidos. Para suporte Unicode completo, seria necessário uma biblioteca externa.

Converter para Minúsculas com Alocação

Use std.ascii.allocLowerString para alocar uma nova string em minúsculas.

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const texto = "Hello World ZIG";
    const lower = try std.ascii.allocLowerString(allocator, texto);
    defer allocator.free(lower);

    try stdout.print("Original:   \"{s}\"\n", .{texto});
    try stdout.print("Minúsculas: \"{s}\"\n", .{lower});
}

Saída esperada:

Original:   "Hello World ZIG"
Minúsculas: "hello world zig"

Converter para Maiúsculas

Use std.ascii.upperString ou std.ascii.allocUpperString.

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Com buffer fixo
    const texto1 = "hello world";
    var buf: [64]u8 = undefined;
    const upper1 = std.ascii.upperString(buf[0..texto1.len], texto1);
    try stdout.print("Buffer fixo: \"{s}\" -> \"{s}\"\n", .{ texto1, upper1 });

    // Com alocação dinâmica
    const texto2 = "zig programming language";
    const upper2 = try std.ascii.allocUpperString(allocator, texto2);
    defer allocator.free(upper2);
    try stdout.print("Alocado:     \"{s}\" -> \"{s}\"\n", .{ texto2, upper2 });
}

Saída esperada:

Buffer fixo: "hello world" -> "HELLO WORLD"
Alocado:     "zig programming language" -> "ZIG PROGRAMMING LANGUAGE"

Capitalizar Primeira Letra

Zig não tem uma função embutida para capitalizar, mas podemos criá-la facilmente.

const std = @import("std");

fn capitalizar(buf: []u8, texto: []const u8) []u8 {
    if (texto.len == 0) return buf[0..0];
    @memcpy(buf[0..texto.len], texto);
    buf[0] = std.ascii.toUpper(texto[0]);
    return buf[0..texto.len];
}

fn capitalizarPalavras(allocator: std.mem.Allocator, texto: []const u8) ![]u8 {
    const resultado = try allocator.alloc(u8, texto.len);
    @memcpy(resultado, texto);

    var capitalizar_proximo = true;
    for (resultado) |*c| {
        if (capitalizar_proximo and std.ascii.isAlphabetic(c.*)) {
            c.* = std.ascii.toUpper(c.*);
            capitalizar_proximo = false;
        } else if (c.* == ' ') {
            capitalizar_proximo = true;
        } else {
            capitalizar_proximo = false;
        }
    }

    return resultado;
}

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Capitalizar primeira letra
    var buf: [64]u8 = undefined;
    const resultado = capitalizar(&buf, "hello world");
    try stdout.print("Capitalizar: \"{s}\"\n", .{resultado});

    // Capitalizar todas as palavras (Title Case)
    const title = try capitalizarPalavras(allocator, "a linguagem zig e incrivel");
    defer allocator.free(title);
    try stdout.print("Title Case:  \"{s}\"\n", .{title});
}

Saída esperada:

Capitalizar: "Hello world"
Title Case:  "A Linguagem Zig E Incrivel"

Converter In-Place (Modificar Slice Mutável)

Quando você tem um slice mutável, pode converter diretamente sem alocação extra.

const std = @import("std");

fn paraMinusculasInPlace(texto: []u8) void {
    for (texto) |*c| {
        c.* = std.ascii.toLower(c.*);
    }
}

fn paraMaiusculasInPlace(texto: []u8) void {
    for (texto) |*c| {
        c.* = std.ascii.toUpper(c.*);
    }
}

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    // Converter in-place para minúsculas
    var texto1 = "HELLO ZIG".*;
    try stdout.print("Antes:  \"{s}\"\n", .{&texto1});
    paraMinusculasInPlace(&texto1);
    try stdout.print("Depois: \"{s}\"\n", .{&texto1});

    // Converter in-place para maiúsculas
    var texto2 = "hello zig".*;
    try stdout.print("\nAntes:  \"{s}\"\n", .{&texto2});
    paraMaiusculasInPlace(&texto2);
    try stdout.print("Depois: \"{s}\"\n", .{&texto2});
}

Saída esperada:

Antes:  "HELLO ZIG"
Depois: "hello zig"

Antes:  "hello zig"
Depois: "HELLO ZIG"

Verificar Tipo de Caractere

O módulo std.ascii também permite verificar o tipo de cada caractere.

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    const chars = [_]u8{ 'A', 'a', '5', ' ', '!', '\n' };

    for (chars) |c| {
        try stdout.print("'{c}': upper={}, lower={}, alpha={}, digit={}, space={}\n", .{
            c,
            std.ascii.isUpper(c),
            std.ascii.isLower(c),
            std.ascii.isAlphabetic(c),
            std.ascii.isDigit(c),
            std.ascii.isWhitespace(c),
        });
    }
}

Saída esperada:

'A': upper=true, lower=false, alpha=true, digit=false, space=false
'a': upper=false, lower=true, alpha=true, digit=false, space=false
'5': upper=false, lower=false, alpha=false, digit=true, space=false
' ': upper=false, lower=false, alpha=false, digit=false, space=true
'!': upper=false, lower=false, alpha=false, digit=false, space=false
'
': upper=false, lower=false, alpha=false, digit=false, space=true

Resumo

FunçãoDescrição
std.ascii.toLower(c)Caractere para minúscula
std.ascii.toUpper(c)Caractere para maiúscula
std.ascii.lowerString(buf, str)String para minúsculas (buffer)
std.ascii.upperString(buf, str)String para maiúsculas (buffer)
std.ascii.allocLowerString(alloc, str)String para minúsculas (alocado)
std.ascii.allocUpperString(alloc, str)String para maiúsculas (alocado)

Veja Também

Continue aprendendo Zig

Explore mais tutoriais e artigos em português para dominar a linguagem Zig.