University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oppgaver.c 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdint.h>
  5. // b
  6. int stringsum(char* str)
  7. {
  8. int sum = 0;
  9. char c;
  10. int i;
  11. for (i = 0; (c = str[i]); ++i)
  12. {
  13. if (c >= 'A' && c <= 'Z')
  14. sum += c - 'A' + 1;
  15. else if (c >= 'a' && c <= 'z')
  16. sum += c - 'a' + 1;
  17. else
  18. return -1;
  19. }
  20. return sum;
  21. }
  22. // c
  23. int distance_between(char* str, char ch)
  24. {
  25. int first = -1;
  26. char c;
  27. int i;
  28. for (i = 0; (c = str[i]); ++i)
  29. {
  30. if (c != ch)
  31. continue;
  32. if (first == -1)
  33. first = i;
  34. else
  35. return i - first;
  36. }
  37. return -1;
  38. }
  39. // d
  40. char* string_between(char* str, char ch)
  41. {
  42. int start = -1;
  43. char c;
  44. int i;
  45. for (i = 0; (c = str[i]); ++i)
  46. {
  47. if (c != ch)
  48. continue;
  49. if (start == -1)
  50. {
  51. start = i;
  52. }
  53. else
  54. {
  55. char* res = malloc(i - start + 1);
  56. memcpy(res, str + start + 1, i - start - 1);
  57. res[i - start - 1] = '\0';
  58. return res;
  59. }
  60. }
  61. return NULL;
  62. }
  63. // e
  64. char** split(char* str)
  65. {
  66. char delim = ' ';
  67. int len = 0;
  68. int start = 0;
  69. char** res = NULL;
  70. char c;
  71. int i;
  72. for (i = 0; (c = str[i]); ++i)
  73. {
  74. if (c != delim)
  75. continue;
  76. len += 1;
  77. res = realloc(res, sizeof(*res) * len);
  78. char* s = malloc(i - start + 1);
  79. memcpy(s, str + start, i - start);
  80. s[i - start] = '\0';
  81. res[len - 1] = s;
  82. start = i + 1;
  83. }
  84. // Add the last item, and null
  85. len += 2;
  86. res = realloc(res, sizeof(*res) * len);
  87. char* s = malloc(i - start + 1);
  88. memcpy(s, str + start, i - start);
  89. s[i - start] = '\0';
  90. res[len - 2] = s;
  91. res[len - 1] = NULL;
  92. return res;
  93. }
  94. // g
  95. void stringsum2(char* str, int* res)
  96. {
  97. int sum = 0;
  98. char c;
  99. int i;
  100. for (i = 0; (c = str[i]); ++i)
  101. {
  102. if (c >= 'A' && c <= 'Z')
  103. sum += c - 'A' + 1;
  104. else if (c >= 'a' && c <= 'z')
  105. sum += c - 'a' + 1;
  106. else
  107. {
  108. *res = -1;
  109. return;
  110. }
  111. }
  112. *res = sum;
  113. }