Advertisement
Guest User

Untitled

a guest
Jan 18th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. stringhe.h
  2. #if !defined STRINGHE_H
  3. #define STRINGHE_H
  4. #define _CRT_SECURE_NO_WARNINGS
  5. #include <stdlib.h>
  6. #include <string.h>
  7. extern char *center(const char *str, size_t n, char c);
  8. #endif // !defined STRINGHE_H
  9.  
  10. stringhe.c
  11. #include "stringhe.h"
  12. void riempi(char *s, char c, size_t pos, size_t n) {
  13. for (unsigned int i = pos; i < pos + n; ++i) {
  14. s[i] = c;
  15. }
  16. }
  17. void stampa_stringa(char *dest, char *origin, size_t pos, size_t n) {
  18. size_t c = 0;
  19. for (unsigned int i = pos; i <pos+n; i++){
  20. dest[i] = origin[c];
  21. c++;
  22. }
  23. }
  24. char *center(const char *str, size_t n, char c) {
  25. if (str == 0) return NULL;
  26. size_t dim = strlen(str), nmeta, count = 0;
  27. nmeta = n - dim;
  28. char *tmp = malloc((dim + 1) * sizeof(char));
  29. strcpy(tmp, str);
  30. char *p = malloc((n+1) * sizeof(char));
  31. if ((dim % 2 == 0 && n % 2 == 0 && count == 0) || (n%2!=0 && (n-dim)%2==0 && count == 0) ) {
  32. riempi(p, c, 0, (nmeta / 2));
  33. stampa_stringa(p, tmp, (nmeta / 2), dim);
  34. riempi(p, c, (nmeta / 2 + dim), (nmeta / 2));
  35. p[n] = 0;
  36. }
  37. if (dim >= n && count == 0) {
  38. p = realloc(p, dim + 1);
  39. stampa_stringa(p, tmp, 0, dim);
  40. p[dim] = 0;
  41. count++;
  42. }
  43. if (dim % 2 == 0 && n % 2 != 0 && count == 0){
  44. riempi(p, c, 0, (nmeta / 2+1));
  45. stampa_stringa(p, tmp, (nmeta / 2+1), dim);
  46. riempi(p, c, (nmeta / 2 + dim+1), (nmeta / 2));
  47. p[n] = 0;
  48. count++;
  49. }
  50. if (dim % 2 != 0 && n % 2 == 0 && count == 0) {
  51. riempi(p, c, 0, (nmeta / 2));
  52. stampa_stringa(p, tmp, (nmeta / 2), dim);
  53. riempi(p, c, (nmeta / 2 + dim), (nmeta / 2+1));
  54. p[n] = 0;
  55. count++;
  56. }
  57. free(tmp);
  58. return p;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement