C++ Exercises: From a list of strings, create a new list with "$" at the beginning and end
Add "$" at Start and End of Each String in Array
Write a C++ program to create a list from a given list of strings where each element has "$" added at the beginning and end position.
Test Data:
Sample Input:
{ "1", "2", "3" , "4" }
Expected Output:
$1$ $2$ $3$ $4$
Sample Solution:
C++ Code :
#include <bits/stdc++.h> // Include all standard C++ libraries
#include <list> // Include the list container
using namespace std; // Using standard namespace
// Function to create a new list where each element has "$" added at the beginning and end
list<string> test(list<string> nums) {
list<string> new_list; // Declare a new list to store modified elements
list<string>::iterator it; // Declare an iterator for traversing the input list 'nums'
// Iterate through 'nums' list and add "$" at the beginning and end of each element
for (it = nums.begin(); it != nums.end(); ++it) {
new_list.push_back("$" + *it + "$"); // Add "$" at the beginning and end
}
return new_list; // Return the new list with modified elements
}
// Function to display the elements of a list
display_list(list<string> g)
{
list<string>::iterator it; // Declare an iterator for traversing the input list 'g'
// Iterate through 'g' list and display each element
for (it = g.begin(); it != g.end(); ++it) {
cout << *it << ' '; // Print each element followed by a space
}
cout << '\n'; // Move to a new line after displaying all elements
}
int main() {
list<string> text = { "1", "2", "3", "4", "5", "6" }; // Initialize a list 'text' with strings
cout << "Original list of elements:\n";
display_list(text); // Display the original list 'text'
list<string> result_list; // Declare a list to store the result of test() function
result_list = test(text); // Call the test() function to modify each element
cout << "\nNew list from the said list where each element has \n$ added at the beginning and end position:\n";
display_list(result_list); // Display the new list with modified elements
return 0; // Return 0 to indicate successful completion of the program
}
Sample Output:
Original list of elements: 1 2 3 4 5 6 New list from the said list where each element has $ added at the beginning and end position: $1$ $2$ $3$ $4$ $5$ $6$
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Multiply each integer in a list three times.
Next: Concatenate three copies of each string in a given list of strings.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics