Está en la página 1de 27

CURSO DE

S
O
M
T
I
R
O
G
L
A

mas de Inform
te
is
S
n
e
a
r
ie
n
e
Facultad Ing
uatemala
G
a
u
g
ti
n
A
o
ri
a
it
Centro Univers
Secciones D y E

Olivet Lpez
ia
c
re
c
u
L
a
Alm
Sistemas
Ingeniera en
anizacional
rg
O
o
g
z
ra
e
id
M.A. L
o en Invest
d
ra
to
c
o
D
to
Candida

Fuente: www.slideshare.net

Ejercicio 1
Escriba
un
programa
que
permita leer una cadena, que
puede contener letras y dgitos,
y luego nos determine la
cantidad de dgitos contenidos
en la cadena.

Ejercicio 2
Escriba
un
programa
permita leer una cadena
caracteres y que luego
determine
e
imprima
cantidad
de
palabras
contiene la cadena.

que
de
nos
la
que

Uso de 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.
2.

Los cdigos para los caracteres que representan


dgitos del 0 al 9 son consecutivos.
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

Definicin de Cadenas

Definicin de cadenas de caracteres.Una cadena de texto es un conjunto de caracteres, tales como ABCDEFG - * $$ %
%65 (letras, smbolos, nmeros, etc.).
En el lenguaje C soporta cadenas de texto utilizando un array (arreglos) de
caracteres que contenga una secuencia seguidas por un carcter \0 o null.
Las cadenas de caracteres deben ser almacenadas en un array pero no todos los
arrays contienen cadenas de caracteres.
Ejemplo:
A

\0

Carcter nulo

Se debern usar las funciones para manejo de cadenas y no tratar de manipular


las cadenas en forma manual desmantelando y ensamblando cadenas:

Declaracin de una cadena de caracteres.


No se puede asignar una cadena a un array del siguiente modo:
Cadena = "ABCDEF" ;
Se debe asignar una cadena a un array del siguiente modo:
Cadena[6] = "ABCDEF" ;
Cadena [6]= A

\0

Diferencia de cadena con una array de caracteres


Es que la cadena de caracteres la longitud del array debe tener el tamao de la
longitud +1 para que se almacene el carcter nul o \0.
Ejemplo:
Cadena[4]=ABCD;
Cadena[4]=A

\0

El array de caracteres debe tener la longitud exacta de caracteres:


Ejemplo:
cadena[4]={ABCDE};
A
cadena[4]=

Interfaces y funciones

Para copiar una constante cadena o copiar una variable de cadena a otra
variable de cadena se debe utilizar la funcin de la biblioteca estndar.
#include <string.h>.
Existen varias funciones que nos ayudan a trabajar con cadenas de caracteres
las ms utilizadas son:
strncpy(),
strncat()
strncmp()

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

Funcin strcpy ( )
Permite copiar una constante de cadena en otra cadena.
strcpy(destino, origen)
#include <stdio.h>
#include <string.h>
void main ()
{
char cadena1[8] = "abcdefg";
char cadena2[8];
strcpy( cadena2, cadena1 );
printf( "cadena2=%s\n",
cadena2 );
printf( "cadena1=%s\n",
cadena1 );
}

strcpy ( ) aade un carcter nulo al final de la cadena. A fin de que no


se produzcan errores en la sentencia anterior, se debe asegurar que el
array tenga elementos suficientes para contener la cadena situada a
su derecha.

Funcin strncmp().
Est funcin compara lxicamente las cadenas de texto:
#include <stdio.h>
#include <string.h>
void main()
{
char s1[4] = "Mira";
char s2[4] = "mira";
int i;
printf("s1=%s\t", s1 );

printf("s2=%s\n", s2 );

i = strcmp( s1, s2 );
printf( "s1 es " );
if( i < 0 )
printf( "menor que" );
else if( i > 0 )
printf( "mayor que" );
else
printf( "igual a" );
printf( " s2\n" );
}

Menor que cero -- si cadena1 es lxicamente menor que cadena2;


Cero -- si cadena1 y cadena2 son lxicamente iguales;
Mayor que cero si cadena1 es lxicamente mayor que cadena2;

Funcin strncat()
Aade una copia de la cadena apuntada por s2 (incluyendo el carcter nulo) al
final de la cadena apuntada por s1. El carcter inicial de s2 sobrescribe el
carcter nulo al final de s1.
Ejemplo:
#include <stdio.h>
#include <string.h>
void main()
{
char s1[11] = "Hola ";
char s2[5] = mundo";
printf( "s1=%s\t", s1 );
printf( "s2=%s\n", s2 );
strcat( s1, s2 );
printf( "s1=%s\n", s1 );
}

Mtodos por teclado y escritura por pantalla


Para ingresar una cadena de caracteres se utiliza
la instruccin
scanf(%s,&variable) se almacena la cadena ingresada hasta la longitud que
se asigno.
Para la impresin se utiliza printf(%s,variable) imprime todos los caracteres
que tenga asignado la variable:
Ejemplo:
#include <stdio.h>
void main()
{
char s1[4];
printf("ingrese la cadena la longitud debe ser menor a 3 digitos\n");
scanf("%s",&s1);
}

printf( "la cadena ingresada es = %s\n", s1 );

Interfaces y funciones

ctype.h: Librera de manejo de


caracteresDescription
Prototype
int isdigit( int c );

Returns true if c is a digit and false otherwise.

int isalpha( int c );

Returns true if c is a letter and false otherwise.

int isalnum( int c );

Returns true if c is a digit or a letter and false otherwise.

int isxdigit( int c );

Returns true if c is a hexadecimal digit character and false otherwise.

int islower( int c );

Returns true if c is a lowercase letter and false otherwise.

int isupper( int c );

Returns true if c is an uppercase letter; false otherwise.

int tolower( int c );

If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower


returns the argument unchanged.

int toupper( int c );

If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper


returns the argument unchanged.

int isspace( int c );

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

int iscntrl( int c );

Returns true if c is a control character and false otherwise.

int ispunct( int c );

Returns true if c is a printing character other than a space, a digit, or a letter and false
otherwise.

int isprint( int c );

Returns true value if c is a printing character including space (' ') and false otherwise.

int isgraph( int c );

Returns true if c is a printing character other than space ( ' ') and false otherwise.

Stdlib.h: Librera de funciones de


conversin
Convierte cadenas de dgitos a enteros y valores de
punto flotante.
Function prototype

Function description

double atof( const char *nPtr );

Converts the string nPtr to double.

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 );

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

Function prototype

Function description

int getchar( void );

Inputs the next character from the standard input and returns it as an integer.

char *gets( char *s );

int putchar( int c );


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

Inputs characters from the standard input into the array s


until a newline or end-of-file character is encountered. A
terminating null character is appended to the array.
Prints the character stored in c.
Prints the string s followed by a newline character.
Equivalent to printf, except the output is stored in the
array s instead of printing it on the screen.
Equivalent to scanf, except the input is read from the array
s instead of reading it from the keyboard.

String.h: Librera de manipulacin de


cadenas
Incluye funciones para:

Manipular cadenas
Bsqueda en cadenas
Manejo de tokens
Determine la longitud de cadenas

Function prototype

Function description

char *strcpy( char


*s1, const char *s2 )
char *strncpy( char
*s1, const char *s2,
size_t n )
char *strcat( char
*s1, const char *s2 )

Copies string s2 into array s1. The value of s1 is returned.

char *strncat( char


*s1, const char *s2,
size_t n )

Copies at most n characters of string s2 into array s1. The value of s1


is returned.
Appends string s2 to array s1. The first character of s2 overwrites the
terminating null character of s1. The value of s1 is returned.
Appends at most n characters of string s2 to array s1. The first
character of s2 overwrites the terminating null character of s1. The
value of s1 is returned.

Funciones de comparacin de
cadenas
int strcmp( const char *s1, const char *s2 );
Compara string
Retorna:

s1 con s2

s1 < s2
Cero,si s1 == s2
Un nmero positivo si s1 > s2
Un nmero negativo si

int strncmp(const char *s1,const char *s2,size_t


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

Funciones de Bsqueda
Function prototype

Function description

char *strchr( const char *s,


int c );

Locates the first occurrence of character c in string s. If c is found, a


pointer to c in s is returned. Otherwise, a NULL pointer is returned.

size_t strcspn( const char


*s1, const char *s2 );

Determines and returns the length of the initial segment of string s1


consisting of characters not contained in string s2.

size_t strspn( const char


*s1, const char *s2 );

Determines and returns the length of the initial segment of string s1


consisting only of characters contained in string s2.

char *strpbrk( const char


*s1, const char *s2 );

Locates the first occurrence in string s1 of any character in string s2.


If a character from string s2 is found, a pointer to the character in
string s1 is returned. Otherwise, a NULL pointer is returned.

char *strrchr( const char *s,


int c );

Locates the last occurrence of c in string s. If c is found, a pointer to c


in string s is returned. Otherwise, a NULL pointer is returned.

char *strstr( const char *s1,


const char *s2 );

Locates the first occurrence in string s1 of string s2. If the string is


found, a pointer to the string in s1 is returned. Otherwise, a NULL
pointer is returned.

char *strtok( char *s1, const


char *s2 );

A sequence of calls to strtok breaks string s1 into tokenslogical


pieces such as words in a line of textseparated by characters
contained in string s2. The first call contains s1 as the first argument,
and subsequent calls to continue tokenizing the same string contain
NULL as the first argument. A pointer to the current token is returned
by each call. If there are no more tokens when the function is called,
NULL is returned.

También podría gustarte