char text[100]; // 100 carateres máximo#define MAX_SIZE 100
...
char text[MAX_SIZE];'\0')
"Abba" é \(\begin{array}{|c|c|c|c|c|c|}\hline \texttt{A} & \texttt{b} & \texttt{b} & \texttt{a} & \texttt{\0} \\\hline \end{array}\)'\0' é um terminador que marca o final da cadeia
char text[6] = { 'H','e','l','l','o','\0' };char text[6] = "Hello";'\0 é automaticamente introduzido no finalchar text[100] = "Hello";
// os carateres restantes são '\0'char text[] = "Hello"; // tamanho 6Para imprimir uma cadeia podemos usar:
puts;printf com o formato "%s"#include <stdio.h>
char text[] = "Hello, world";
puts(text);Alternativa:
printf("%s\n", text);Podemos usar fgets() para ler cadeias de carateres.
#include <stdio.h>
#define MAX_SIZE 100
...
char text[MAX_SIZE];
fgets(text, MAX_SIZE, stdin);stdin é a entrada padrão)Vamos definir pequenas funções para processar cadeias de carateres.
unsigned comprimento(char str[]);<string.h>): size_t strlen(char str[]);size_t é um inteiro sem sinal (porque o comprimento nunca é negativo)unsigned comprimento(char str[])
{
unsigned i = 0;
while(str[i] != '\0')
i++;
return i;
} unsigned contar_espacos(char str[]);'\0'unsigned contar_espacos(char str[])
{
unsigned espacos = 0;
for(int i=0; str[i]!='\0'; i++)
{
if(str[i] == ' ')
espacos ++;
}
return espacos;
}"abc123" deve ser transformado em "321cba" void inverter(char str[]);inverter não retorna qualquer valorCuidados:
void inverter(char str[])
{
int i = 0, j;
j = comprimento(str) - 1;
// atenção: j pode ser negativo!
while (i < j) {
char ch = str[i];
str[i] = str[j];
str[j] = ch;
i ++;
j --;
}
}#include <stdio.h>
#define MAX_SIZE 1000 // tamanho máximo
int main(void) {
char text[MAX_SIZE];
fgets(text, MAX_SIZE, stdin); // ler
puts(text); // imprimir original
inverter(text); // inverter
puts(text); // imprimir invertido
}