|
| 1 | +#include <iostream> |
| 2 | + |
| 3 | +using std::cout; |
| 4 | +using std::endl; |
| 5 | + |
| 6 | +typedef char * arrayString; |
| 7 | + |
| 8 | +void append(arrayString &str, char ch); |
| 9 | +void concatenate(arrayString &str1, arrayString str2); |
| 10 | +char characterAt(arrayString str, int position); |
| 11 | +int getLength(arrayString str); |
| 12 | + |
| 13 | +int main() |
| 14 | +{ |
| 15 | + arrayString str = new char[5]; |
| 16 | + str[0] = 'T'; str[1] = 'e'; str[2] = 's'; str[3] = 't'; str[4] = 0; |
| 17 | + cout << "The string: " << str << endl; |
| 18 | + |
| 19 | + cout << "Character at position " << 1 << " is " << characterAt(str, 1) << endl; |
| 20 | + |
| 21 | + cout << "Before append: " << str << endl; |
| 22 | + append(str, '!'); |
| 23 | + cout << "After append: " << str << endl; |
| 24 | + |
| 25 | + arrayString str1 = new char[5]; |
| 26 | + str1[0] = 'T'; str1[1] = 'e'; str1[2] = 's'; str1[3] = 't'; str1[4] = 0; |
| 27 | + |
| 28 | + arrayString strToAdd = new char[4]; |
| 29 | + strToAdd[0] = 'b'; strToAdd[1] = 'e'; strToAdd[2] = 'd'; strToAdd[3] = 0; |
| 30 | + |
| 31 | + cout << "Before concatenate: " << str1 << endl; |
| 32 | + cout << "String to add: " << strToAdd << endl; |
| 33 | + concatenate(str1, strToAdd); |
| 34 | + cout << "After concatenate: " << str1 << endl; |
| 35 | + cout << (void*) str1 << " " << (void*)strToAdd << endl; |
| 36 | + |
| 37 | +} |
| 38 | + |
| 39 | +char characterAt(arrayString str, int position) |
| 40 | +{ |
| 41 | + return str[position]; |
| 42 | +} |
| 43 | + |
| 44 | +void append(arrayString &str, char ch) |
| 45 | +{ |
| 46 | + int oldLen = getLength(str); |
| 47 | + arrayString newStr = new char[oldLen + 2]; |
| 48 | + |
| 49 | + for (int i = 0; i < oldLen; i++) |
| 50 | + { |
| 51 | + newStr[i] = str[i]; |
| 52 | + } |
| 53 | + newStr[oldLen] = ch; |
| 54 | + newStr[oldLen + 1] = 0; |
| 55 | + delete[] str; |
| 56 | + str = newStr; |
| 57 | +} |
| 58 | + |
| 59 | +void concatenate(arrayString &str1, arrayString str2) |
| 60 | +{ |
| 61 | + int len1 = getLength(str1); |
| 62 | + int len2 = getLength(str2); |
| 63 | + int newLen = len1 + len2; |
| 64 | + arrayString newStr = new char[newLen+1]; |
| 65 | + for (int i = 0; i < len1; i++) |
| 66 | + { |
| 67 | + newStr[i] = str1[i]; |
| 68 | + } |
| 69 | + for (int i = len1; i < newLen; i++) |
| 70 | + { |
| 71 | + newStr[i] = str2[i - len1]; |
| 72 | + } |
| 73 | + newStr[newLen] = 0; |
| 74 | + delete[] str1; |
| 75 | + str1 = newStr; |
| 76 | +} |
| 77 | + |
| 78 | +int getLength(arrayString str) |
| 79 | +{ |
| 80 | + int len = 0; |
| 81 | + while(str[len] != 0) |
| 82 | + { |
| 83 | + len++; |
| 84 | + } |
| 85 | + return len; |
| 86 | +} |
| 87 | + |
0 commit comments