Chapter 16 - Worked Exercises 1
Exercise 1 - Recap
Part 0 - Terminology
Explain what is meant by the following terms in the context of strings:
Copying
Concatenating
Truncating
Finding
Part 1 - Copying
Write a function string_copy that returns a pointer to a dynamically allocated character array with the contents of the string original.
const char* string_copy(const char* original) {
// ...
}Show how copying is achieved with the std::string class.
Part 2 - Concatenating
Write a function string_concatenate that returns a pointer to a dynamically allocated character array with the contents of first and second concatenated:
const char* string_concatenate(const char* first, const char* second) {
// ...
};Show how concatenation is achieved with the std::string class.
Part 3 - Truncating
Write a function string_truncate that returns a pointer to a dynamically allocated character array with the contents of original truncated to the range specified by integer parameters from and to.
The range copied should be [from, to), meaning inclusive of from but not inclusive of to.
const char* string_truncate(const char* original, int from, int to) {
// ...
}Show how truncating is achieved with the std::string class.
Exercise 2 - String Splitting
Write a function that splits a string representing a sentence, into a vector of strings each corresponding to a word in the sentence:
std::vector<std::string> splitString(std::string sentence) {
// ...
}Usage
int main() {
std::cout << "Enter a sentence:" << std::endl;
std::string sentence;
std::getline(std::cin, sentence);
std::vector<std::string> words = splitString(sentence);
for (auto word: words) {
std::cout << word << std::endl;
}
}Exercise 3 - Palindrome
Write a function to check if a given string is a palindrome or not.
bool palindrome(std::string word) {
// ...
}Exercise 4 - Word Manipulation
Part 1
Write a function that counts the number of vowels in a sentence.
int numVowels(std::string sentence);Part 2
Write a function that converts every alternate character of a string into uppercase.
void toAltUpper(std::string& sentence);Exercise 5
Write a program that displays the position of every occurrence of character 'a' in a string:
void displayAllAs(std::string sentence);Example
Enter a sentence:
Good day String! Today is beautiful!
^ ^ ^Last updated
Was this helpful?