/****************************************************************************
PROGRAMA:	p_c_06.c
AUTOR:		Kiko
FECHA:		13.10.94
FINALIDAD:	Soluci¢n al problema 06 de la hoja de problemas de C
****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LONG 100

char s1[MAX_LONG], s2[MAX_LONG];

/***************************************************************************/
	int slen(char *str) {
	char *s = str;

	while (*s != '\0')
		s++;
	return(s - str);
	}
/***************************************************************************/
	void scat(char *str1, char *str2) {
	char *s = str1, *r = str2;	/* Para recorrer las cadenas */

	while (*s != '\0')
		s++;

	while (*r != '\0') {
		*s = *r;
		r++;
		s++;
	}

	*s = '\0';		/* Finalizar la cadena correctamente */
	}
/***************************************************************************/
char *sleft(char *str, int n) {
	char *s = str, *mem, *ini;
	int longitud;

	mem = (char *)malloc((n + 1) * sizeof(char));
	if (mem == NULL) {
		printf("Error: No hay memoria suficiente.\n");
		exit(-1);
	}
	ini = mem;

	for (longitud = 0; ((*s != '\0') && (longitud < n)); s++) {
		*mem = *s;
		mem++;
		longitud++;
	}
	*mem = '\0';
	return(ini);
}
/***************************************************************************/
char *sright(char *str, int n) {
	char *s;
	char *mem, *ini_cad;
	int num_char;

	ini_cad = str;

	mem = (char *)malloc((n + 1) * sizeof(char));
	if (mem == NULL) {
		printf("Error: No hay memoria suficiente.\n");
		exit(-1);
	}
	mem += (n + 1);

	s = str;
	while (*s != '\0')
		s++;

	ini_cad = str;
	num_char = 0;
	while ((s != ini_cad) && (num_char < n)) {
		*mem = *s;
		mem--;
		s--;
		num_char++;
	}
	*mem = *s;
	return(mem);
}
/***************************************************************************/

void main(void) {

strcpy(s1, "Adi¢s ");
strcpy(s2, "Mundo cruel");
scat(s1, s2);
printf("s1: %s\n", s1);
printf("3 primeros de s1: %s\n", sleft(s1, 3));
printf("3 £ltimos de s1: %s\n", sright(s1, 3));
}


