# Chapter 16 - Worked Exercises 1

## Exercise 1 - Recap&#x20;

### Part 0 - Terminology

Explain what is meant by the following terms in the context of strings:

* Copying
* Concatenating&#x20;
* Truncating&#x20;
* Finding&#x20;

### 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`.&#x20;

```cpp
const char* string_copy(const char* original) {
   // ... 
}
```

Show how copying is achieved with the `std::string` class.&#x20;

### Part 2 - Concatenating&#x20;

Write a function `string_concatenate` that returns a **pointer** to a dynamically allocated character array with the contents of `first` and `second` concatenated:

```cpp
const char* string_concatenate(const char* first, const char* second) {
    // ...
};
```

Show how concatenation is achieved with the `std::string` class.

### Part 3 - Truncating&#x20;

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`.&#x20;

The range copied should be `[from, to)`, meaning inclusive of `from` but not inclusive of `to`.

```cpp
const char* string_truncate(const char* original, int from, int to) {
   // ...
}
```

Show how truncating is achieved with the `std::string` class.&#x20;

## Exercise 2 - String Splitting&#x20;

Write a function that splits a string representing a sentence, into a vector of strings each corresponding to a word in the sentence:

```cpp
std::vector<std::string> splitString(std::string sentence) {
    // ...
}
```

### Usage

```cpp
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&#x20;

Write a function to check if a given string is a palindrome or not.

{% hint style="info" %}
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar.
{% endhint %}

```cpp
bool palindrome(std::string word) {
    // ...
}
```

## Exercise 4 - Word Manipulation

### Part 1&#x20;

Write a function that counts the number of vowels in a sentence.&#x20;

```cpp
int numVowels(std::string sentence);
```

### Part 2&#x20;

Write a function that converts every alternate character of a string into uppercase.

```cpp
void toAltUpper(std::string& sentence);
```

## Exercise 5&#x20;

Write a program that displays the position of every occurrence of character 'a' in a string:

```cpp
void displayAllAs(std::string sentence);
```

### Example&#x20;

```cpp
Enter a sentence: 
Good day String! Today is beautiful!
      ^             ^       ^
```
