Exercies on C-String (Lecture 15)
I won't post the solution for the exercises, if you have questions, go
to TA sections
1.
(a) What is a string?
(b) A C-String is an array of charaters, yes or no?
(c) Can abitrary sequence of character array a C-String?
(d) Can you define a C-String?
2.
Which of the following can be a C-String?
(a)
char a[10] = "Charles";
(b)
char a[] = {'a', 'b', 'c'};
(c)
char a[] = {'a', 'b', 'c', 'd', '\0'};
(d)
char array[5] = {'a', 'b','\0', 'X', 'Y'};
(e)
char array[5] = {'a', 'b', 'c', 'd', 'e'};
array[4] = '\0';
(3) What is the output of the following programs? Indicate the errors if you think
that the programs do not work properly.
(a)
#include<iostream>
using namespace std;
int main() {
char name[] = "Amy";
cout << "Hello " << name << "!\n";
return 0;
}
|
(b)
#include<iostream>
using namespace std;
int main() {
char name[] = "Diana";
for(int i = 0; i < 6; i++) {
cout << i << " " << name[i] << endl;
}
return 0;
}
|
(c)
#include<iostream>
using namespace std;
int main() {
char name[] = "David";
name[2] = '2';
name[3] = '3';
cout << name << endl;
return 0;
}
|
(d)
#include<iostream>
using namespace std;
int main() {
char name[] = "David";
name[2] = '2';
name[3] = '\0';
cout << name << endl;
return 0;
}
|
(e)
#include<iostream>
using namespace std;
int main() {
char array[] = {'a', 'b', 'c', 'd', '\0', 'e', 'f'};
cout << array;
cout << endl;
array[4] = '4';
array[6] = '\0';
cout << array;
cout << endl;
return 0;
}
|
(f)
#include<iostream>
using namespace std;
int main() {
int array[] = {1,2,3};
cout << array;
cout << endl;
return 0;
}
|
(4) Find out the compiling errors or runtime error.
Circle the errors. Indicate whether they are compiling error or runtime error.
Write your corrections.
(a)
#include<iostream>
using namespace std;
int main() {
char a[15];
a = "Absolute C++";
return 0;
}
|
(b)
#include<iostream>
using namespace std;
int main() {
char a[4]="Mary";
cout << a;
return 0;
}
|
(c)
#include<iostream>
using namespace std;
int main() {
char a[4]={'M','a','r','y'};
cout << a;
return 0;
}
|
(5)
(a)
Write a function
int count(char string[], char ch)
The function returns the occurence of ch in of the C-String string
(b)
Write a function
void replace(char string[], char oldChar, char newChar)
The function replaces oldChar of the C-String string
by newChar.
Example, if string is "Hello", then after the calling
of replace(string, 'l', 'k'), string becomes
"Hekko".
(c)
Write a function
void reverse(char string[], char reverseString[])
the reverseString is the reverse of the C-String string.
e.g. if string is "Hello", then reverseString is
"olleH"
You can assume that reverseString has enough space. Don't forget the null
('\0') at the end of the reverseString !