Strings: char arrays and the null terminator · Strings: arrays de chars e terminador nulo
Text is an array of chars
- C has no separate string type. A string is just an array of
char. char word[] = "hi";actually stores'h','i', and a hidden'\0'at the end.- You can read one character at a time with an index, exactly like any array.
Texto é uma matriz de chars
- C não tem um tipo separado para strings. Uma string é apenas uma matriz de
char. char word[] = "hi";na verdade armazena'h','i'e um'\0'oculto no final.- Você pode ler um caractere por vez com um índice, exatamente como qualquer matriz.
The invisible terminator '\0'
- Every C string ends with a special null terminator, written
'\0'(a byte equal to0). - It marks where the text stops. The word
"hi"takes three bytes:'h','i','\0'. - Functions know a string has ended when they reach
'\0'— there is no stored length.
O terminador invisível '\0'
- Toda string C termina com um terminador nulo especial, escrito
'\0'(um byte igual a0). - Ele marca onde o texto para. A palavra
"hi"ocupa três bytes:'h','i','\0'. - Funções sabem que uma string acabou quando encontram
'\0'— não há comprimento armazenado.
Walking a string
- To visit each character, loop an index while
s[i] != '\0'. - When
s[i]becomes'\0', you have reached the end — stop. - This is how you count characters, search, or copy a string by hand.
Percorrendo uma string
- Para visitar cada caractere, faça um loop com um índice enquanto
s[i] != '\0'. - Quando
s[i]se torna'\0', você chegou ao fim — pare. - É assim que você conta caracteres, busca ou copia uma string manualmente.
#include <stdio.h>
int main(void) {
char word[] = "hello";
int len = 0;
while (word[len] != '\0') { // stop at the terminator
len++;
}
printf("%d\n", len); // 5
return 0;
}
The <string.h> toolbox
<string.h>has ready-made helpers:strlen(s)(length),strcpy(dst, src)(copy),strcmp(a, b)(compare),strcat(dst, src)(join).strcmp(a, b)returns0when the two strings are equal — handy in tests.- These all rely on the
'\0'terminator to know where each string ends.
O kit de ferramentas <string.h>
<string.h>possui helpers prontos:strlen(s)(comprimento),strcpy(dst, src)(cópia),strcmp(a, b)(comparação),strcat(dst, src)(junção).strcmp(a, b)retorna0quando as duas strings são iguais — útil em testes.- Todas elas dependem do terminador
'\0'para saber onde cada string termina.
Common mistakes
- A string needs one extra byte for
\0: a 5-letter word needschar[6]. - Compare strings with
strcmp, not==.
Erros comuns
- Uma string precisa de um byte extra para o terminador
\0: uma palavra de 5 letras precisa dechar[6]. - Compare strings com
strcmp, não com==.
Now you try
- To change a string in place, the caller must pass a writable
chararray, not a fixed text. - Stop your loops at
'\0'. Do not write amain— the checker provides one.
Agora você tenta
- Para alterar uma string in-place, o chamador deve passar uma matriz
chargravável, não um texto fixo. - Pare seus loops no terminador
'\0'. Não escreva ummain— o verificador fornece um.
Strings are arrays of characters · Strings são arrays de caracteres
Index each character from 0; the slice shows a range of chars. · Indexe cada caractere de 0; a fatia mostra um intervalo de chars.
Complete int count_char(const char *s, char c) so it returns how many times c appears in the string s. Loop until you reach the end of the string. Do not · não write a main. · Complete int count_char(const char *s, char c) para que retorne quantas vezes c aparece na string s. Loop até atingir o fim da string. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int my_strlen(const char *s) so it returns the length of s without calling strlen. Walk the array until you reach the end. Do not · não write a main. · Complete int my_strlen(const char *s) para que retorne o comprimento de s sem chamar strlen. Percorra o array até atingir o fim. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete void reverse_str(char *s) so it reverses the characters of s in place. Find the length, then swap from both ends toward the middle. Do not · não write a main. · Complete void reverse_str(char *s) para inverter os caracteres de s in-place. Encontre o comprimento, depois troque das duas extremidades em direção ao meio. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.