Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- stringhe.h
- #if !defined STRINGHE_H
- #define STRINGHE_H
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdlib.h>
- #include <string.h>
- extern char *center(const char *str, size_t n, char c);
- #endif // !defined STRINGHE_H
- stringhe.c
- #include "stringhe.h"
- void riempi(char *s, char c, size_t pos, size_t n) {
- for (unsigned int i = pos; i < pos + n; ++i) {
- s[i] = c;
- }
- }
- void stampa_stringa(char *dest, char *origin, size_t pos, size_t n) {
- size_t c = 0;
- for (unsigned int i = pos; i <pos+n; i++){
- dest[i] = origin[c];
- c++;
- }
- }
- char *center(const char *str, size_t n, char c) {
- if (str == 0) return NULL;
- size_t dim = strlen(str), nmeta, count = 0;
- nmeta = n - dim;
- char *tmp = malloc((dim + 1) * sizeof(char));
- strcpy(tmp, str);
- char *p = malloc((n+1) * sizeof(char));
- if ((dim % 2 == 0 && n % 2 == 0 && count == 0) || (n%2!=0 && (n-dim)%2==0 && count == 0) ) {
- riempi(p, c, 0, (nmeta / 2));
- stampa_stringa(p, tmp, (nmeta / 2), dim);
- riempi(p, c, (nmeta / 2 + dim), (nmeta / 2));
- p[n] = 0;
- }
- if (dim >= n && count == 0) {
- p = realloc(p, dim + 1);
- stampa_stringa(p, tmp, 0, dim);
- p[dim] = 0;
- count++;
- }
- if (dim % 2 == 0 && n % 2 != 0 && count == 0){
- riempi(p, c, 0, (nmeta / 2+1));
- stampa_stringa(p, tmp, (nmeta / 2+1), dim);
- riempi(p, c, (nmeta / 2 + dim+1), (nmeta / 2));
- p[n] = 0;
- count++;
- }
- if (dim % 2 != 0 && n % 2 == 0 && count == 0) {
- riempi(p, c, 0, (nmeta / 2));
- stampa_stringa(p, tmp, (nmeta / 2), dim);
- riempi(p, c, (nmeta / 2 + dim), (nmeta / 2+1));
- p[n] = 0;
- count++;
- }
- free(tmp);
- return p;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement