C++ Exercises: Insert a dash character (-) between two odd numbers in a given string of numbers
C++ String: Exercise-12 with Solution
Write a C++ program to insert a dash character (-) between two odd numbers in a given string of numbers.
Pictorial Presentation:
Sample Solution:
C++ Code :
#include <iostream>
#include <string>
using namespace std;
string Insert_dash(string num_str) {
string result_str = num_str;
for (int x = 0; x < num_str.length() - 1; x++)
{
if ((num_str[x] == '1' || num_str[x] == '3' || num_str[x] == '5' || num_str[x] == '7' || num_str[x] == '9') && (num_str[x + 1] == '1' || num_str[x + 1] == '3' || num_str[x + 1] == '5' || num_str[x + 1] == '7' || num_str[x + 1] == '9'))
{
result_str.insert(x+1,"-");
num_str = result_str;
}
}
return result_str;
}
int main() {
cout << "Original number-123456789 : Result-> "<< Insert_dash("123456789") << endl;
cout << "\nOriginal number-1345789 : Result-> "<< Insert_dash("1345789") << endl;
cout << "\nOriginal number-1345789 : Result-> "<< Insert_dash("34635323928477") << endl;
return 0;
}
Sample Output:
Original number-123456789 : Result-> 123456789 Original number-1345789 : Result-> 1-345-789 Original number-1345789 : Result-> 3463-5-323-92847-7
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to find a word in a given string which has the highest number of repeated letters.
Next: Write a C++ program to change the case (lower to upper and upper to lower cases) of each character of a given string.
What is the difficulty level of this exercise?