Strings: char arrays and the null terminator · Cadenas: arreglos de caracteres y el 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.
El texto es un array de chars
- C no tiene un tipo de cadena separado. Una cadena es simplemente un array de
char. char word[] = "hi";en realidad almacena'h','i'y un'\0'oculto al final.- Puedes leer un carácter a la vez usando un índice, exactamente como con cualquier array.
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.
El terminador invisible '\0'
- Cada cadena en C termina con un terminador nulo especial, escrito
'\0'(un byte igual a0). - Marca dónde termina el texto. La palabra
"hi"ocupa tres bytes:'h','i','\0'. - Las funciones saben que una cadena ha terminado cuando alcanzan
'\0'— no hay longitud almacenada.
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.
Recorrer una cadena
- Para visitar cada carácter, itera un índice mientras
s[i] != '\0'. - Cuando
s[i]sea igual a'\0', has llegado al final — detente. - Así es como cuentas caracteres, buscas o copias una cadena 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.
El kit de herramientas <string.h>
<string.h>tiene ayudantes predefinidos:strlen(s)(longitud),strcpy(dst, src)(copia),strcmp(a, b)(comparación),strcat(dst, src)(concatenación).strcmp(a, b)devuelve0cuando las dos cadenas son iguales — útil en pruebas.- Todas estas dependen del
'\0'para saber dónde termina cada cadena.
Common mistakes
- A string needs one extra byte for
\0: a 5-letter word needschar[6]. - Compare strings with
strcmp, not==.
Errores comunes
- Una cadena necesita un byte extra para
\0: una palabra de 5 letras necesitachar[6]. - Compara cadenas con
strcmp, no con==.
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.
Ahora tú intentas
- Para modificar una cadena in situ, el llamada debe pasar un array
charescribible, no un texto fijo. - Detén tus bucles en
'\0'. No escribas unmain— el verificador proporciona uno.
Strings are arrays of characters · Las cadenas son arreglos de caracteres
Index each character from 0; the slice shows a range of chars. · Indexar cada carácter desde 0; la rebanada muestra un rango de caracteres.
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 · no write a main. · Completa int count_char(const char *s, char c) para que devuelva cuántas veces aparece c en la cadena s. Itera hasta llegar al final de la cadena. No escribas un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 · no write a main. · Completa int my_strlen(const char *s) para que devuelva la longitud de s sin llamar a strlen. Recorre el arreglo hasta llegar al final. No escribas un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 · no write a main. · Completa void reverse_str(char *s) para que invierta los caracteres de s in situ. Encuentra la longitud, luego intercambia desde ambos extremos hacia el centro. No escribas un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.