Está en la página 1de 15

Caracteres y Cadenas

Conceptos Bsicos
Caracteres
Valor entero representado como caracter entre comillas simples. Por ejemplo: 'z' representa al valor entero de z Internamente se representa como un tipo de dato enumerado usando el cdigo ASCII (cdigo estndar americano para el intercambio de informacin).

Cadenas
Es un arreglo de caracteres que:
Puede incluir letras, dgitos y caracteres especiales (*, /, $) Tiene un puntero al primer caracter Cuyo valor de la cadena es la direccin de memoria del primer elemento.

Propiedades Importantes del Cdigo ASCII


1. Los cdigos para los caracteres que representan dgitos del 0 al 9 son consecutivos. 2. Las letras en el alfabeto estn divididos en dos rangos: uno para las maysculas (A-Z) y otro para las minsculas (a-z). Sin embargo dentro de cada rango los valores ASCII son consecutivos.

Constantes de Tipo Caracter


Es un estndar para referirse a un carcter especfico en C. Para referirse al cdigo ASCII de la letra A, se especifica A, el cual es el 65. Para referirse al cdigo del carcter 9, de forma similar, 9.

CUIDADO: El referirse al carcter, no es lo mismo que referirse al valor entero. El 9 es diferente del 9.

Operaciones con Caracteres


Se puede: Sumar un entero a un carcter Restar un entero de un caracter Restar un caracter de otro Comparar dos caracteres entre s

CUIDADO: Al sumar o restar el resultado no debe salirse del rango de representacin ASCII

Manejo de Cadenas
Definicin
Como un arreglo de caracteres o una variable de tipo char *
char color[] = "blue"; char *colorPtr = "blue";

Recuerde que una cadena se representa como un arreglo de caracteres y termina con '\0'
color tiene 5 elementos

Lectura
Utilizando scanf
scanf("%s", cadena);

Copia la entrada en el arreglo cadena[] No se necesita el & (porque una cadena es un puntero)

Recuerde dejar espacio en el arreglo para el fin de cadena'\0

Escritura
Utilizando printf
printf(%s,cadena);

Ejemplos
char RandomLetra(void) { return (RandomInteger (A, Z)); } bool esMayuscula (char ch) { return (ch >= A && ch <=Z); }

bool esDigito (char ch) { return (ch >= 0 && ch <=9); }

bool esMinuscula (char ch) { return (ch >= a && ch <=z); }

Interfaces tiles

La interfaz ctype.h
Contiene un gran nmero de funciones para determinar el tipo de carcter, entre las principales tenemos:

islower(ch) retorna TRUE si el carcter ch es minscula isupper(ch) retorna TRUE si el carcter ch es mayscula isalpha(ch) retorna TRUE si ch es un valor alfabtico isdigit(ch) retorna TRUE si ch es un dgito isalnum(ch) retorna TRUE si ch es un valor alfanumrico
ispunct(ch) retorna TRUE si ch es un smbolo de puntuacin isspace(ch) retorna TRUE si ch es un carcter en blanco

ctype.h: Librera de manejo de caracteres


Prototype
int isdigit( int c ); int isalpha( int c ); int isalnum( int c ); int isxdigit( int c ); int islower( int c ); int isupper( int c ); int tolower( int c );

Description
Returns true if c is a digit and false otherwise. Returns true if c is a letter and false otherwise. Returns true if c is a digit or a letter and false otherwise. Returns true if c is a hexadecimal digit character and false otherwise. Returns true if c is a lowercase letter and false otherwise. Returns true if c is an uppercase letter; false otherwise. If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower returns the argument unchanged. If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper returns the argument unchanged. Returns true if c is a white-space characternewline ( '\n' ), space ( ' ' ), form feed ('\f' ), carriage return ( '\r' ), horizontal tab ( '\t' ), or vertical tab ( '\v' )and false otherwise Returns true if c is a control character and false otherwise. Returns true if c is a printing character other than a space, a digit, or a letter and false otherwise. Returns true value if c is a printing character including space ( ' ' ) and false otherwise. Returns true if c is a printing character other than space ( ' ') and false otherwise.

int toupper( int c );

int isspace( int c );

int iscntrl( int c ); int ispunct( int c );

int isprint( int c ); int isgraph( int c );

Stdlib.h: Librera de funciones de conversin Convierte cadenas de dgitos a enteros y valores de punto flotante.
Function prototype
double atof( const char *nPtr ); int atoi( const char *nPtr ); long atol( const char *nPtr ); double strtod( const char *nPtr, char **endPtr ); long strtol( const char *nPtr, char **endPtr, int base ); unsigned long strtoul( const char *nPtr, char **endPtr, int base );

Function description
Converts the string nPtr to double . Converts the string nPtr to int. Converts the string nPtr to long int . Converts the string nPtr to double. Converts the string nPtr to long. Converts the string nPtr to unsigned long.

stdio.h
F ctio rotot F ctio d scri tio
int getchar( void ); char *gets( char *s );

Inputs the next character rom the standard input and returns it as an integer . Inputs characters rom the standard input into the array s until a ne line or end-o - ile character is encountered. A terminating null character is appended to the array. Prints the character stored in c. Prints the string s ollo ed by a ne line character. Equivalent to printf, except the output is stored in the array s instead o printing it on the screen. Equivalent to scanf, except the input is read rom the array s instead o reading it rom the keyboard.

int putchar( int c ); int puts( const char *s ); int sprintf( char *s, const char *format, ... ); int sscanf( char *s, const char *format, ... );

String.h: Librera de manipulacin de cadenas


Incluye funciones para:
Manipular cadenas Bsqueda en cadenas Manejo de tokens Determine la longitud de cadenas
Function description
Copies string s2 into array s1. The value o s1 is returned. Copies at most n characters o string s2 into array s1. The value o s1 is returned. Appends string s2 to array s1. The irst character o s2 over rites the terminating null character o s1. The value o s1 is returned. Appends at most n characters o string s2 to array s1. The irst character o s2 over rites the terminating null character o s1. The value o s1 is returned.

Function prototype
char *strcpy( char *s1, const char *s2 ) char *strncpy( char *s1, const char *s2, size_t n ) char *strcat( char *s1, const char *s2 ) char *strncat( char *s1, const char *s2, size_t n )

Funciones de comparacin de cadenas


int strcmp( const char *s1, const char *s2 );

Compara string s1 con s2 Retorna:


Un nmero negativo si s1 < s2 Cero,si s1 == s2 Un nmero positivo si s1 > s2
int strncmp(const char *s1,const char *s2,size_t n);

Compara n caracteres de s1 en s2 Retorna valores como los anteriores

Function rotot

Funciones de Bsqueda
e Function descri tion
Locates the irst occurrence o character c in string s. I c is ound, a pointer to c in s is returned. ther ise, a NULL pointer is returned. Determines and returns the length o the initial segment o string s1 consisting o characters not contained in string s2. Determines and returns the length o the initial segment o string s1 consisting only o characters contained in string s2. Locates the irst occurrence in string s1 o any character in string s2. I a character rom string s2 is ound, a pointer to the character in string s1 is returned. ther ise, a NULL pointer is returned.

char *strchr( const char *s, int c ); size_t strcspn( const char *s1, const char *s2 ); size_t strspn( const char *s1, const char *s2 ); char *strpbrk( const char *s1, const char *s2 );

char *strrchr( const char *s, Locates the last occurrence o c in string s . I c is ound, a pointer to c int c ); in string s is returned. ther ise, a NULL pointer is returned. char *strstr( const char *s1, Locates the irst occurrence in string s1 o string s2 . I the string is const char *s2 ); ound, a pointer to the string in s1 is returned. ther ise, a NULL

pointer is returned.
char *strtok( char *s1, const A sequence o calls to strtok breaks string s1 into tokens logical char *s2 ); pieces such as ords in a line o text separated by characters contained in string s2 . The irst call contains s1 as the irst argument,

and subsequent calls to continue tokenizing the same string contain NULL as the irst argument. A pointer to the current token is returned by each call. I there are no more tokens hen the unction is called, NULL is returned.

También podría gustarte