Q:

Write a C++ program to insert a dash character (-) between two odd numbers in a given string of numbers

0

Write a C++ program to insert a dash character (-) between two odd numbers in a given string of numbers

Sample Output:

Original number-123456789 : Result-> 123456789

Original number-1345789 : Result-> 1-345-789

Original number-1345789 : Result-> 3463-5-323-92847-7

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now