-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_0_variable_length_string.cpp
109 lines (82 loc) · 2.2 KB
/
4_0_variable_length_string.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
typedef char * arrayString;
void append(arrayString &str, char ch);
void concatenate(arrayString &str1, arrayString str2);
char characterAt(arrayString str, int position);
int length(arrayString str);
int main()
{
arrayString str = new char[5];
str[0] = 'T'; str[1] = 'e'; str[2] = 's'; str[3] = 't'; str[4] = 0;
cout << "The string: " << str << endl;
cout << "Character at position " << 1 << " is " << characterAt(str, 1) << endl;
cout << "Before append: " << str << endl;
append(str, '!');
cout << "After append: " << str << endl;
arrayString str1 = new char[5];
str1[0] = 'T'; str1[1] = 'e'; str1[2] = 's'; str1[3] = 't'; str1[4] = 0;
arrayString strToAdd = new char[4];
strToAdd[0] = 'b'; strToAdd[1] = 'e'; strToAdd[2] = 'd'; strToAdd[3] = 0;
cout << "Before concatenate: " << str1 << endl;
cout << "String to add: " << strToAdd << endl;
concatenate(str1, strToAdd);
cout << "After concatenate: " << str1 << endl;
for (int i = 0; i < 8; i++)
{
cout << "index " << i << endl;
cout << "char " << str1[i] << endl;
}
cout << (void*) str1 << " " << (void*)strToAdd << endl;
delete[] str;
delete[] str1;
delete[] strToAdd;
cin.get();
return 0;
}
char characterAt(arrayString str, int position)
{
return str[position-1];
}
void append(arrayString &str, char ch)
{
int oldLen = length(str);
arrayString newStr = new char[oldLen + 2];
for (int i = 0; i < oldLen; i++)
{
newStr[i] = str[i];
}
newStr[oldLen] = ch;
newStr[oldLen + 1] = 0;
delete[] str;
str = newStr;
}
void concatenate(arrayString &str1, arrayString str2)
{
int len1 = length(str1);
int len2 = length(str2);
int newLen = len1 + len2;
arrayString newStr = new char[newLen+1];
for (int i = 0; i < len1; i++)
{
newStr[i] = str1[i];
}
for (int i = len1; i < newLen; i++)
{
newStr[i] = str2[i - len1];
}
newStr[newLen] = 0;
delete[] str1;
str1 = newStr;
}
int length(arrayString str)
{
int len = 0;
while(str[len] != 0)
{
len++;
}
return len;
}