Replacing a digit in a number with another digit in C++

In this CPP tutorial, we are going to discuss how to replace a digit in a number with any other digit.

Integer to String Conversion

To convert an integer to a string we use t0_string() command.

Syntax:-

to_string( num );

Here, integer num will convert to the string.

Ex:-

int num;

cin>>num;

string s = to_string( num );

Now, num will convert to string and s holds its value as a string. Now, we can apply string operations on num.

String To Integer Conversion

To convert string to an integer we use stoi() command.

Syntax:-

   stoi( str );

Here, str is the string to which we need to convert to integer.

Ex:-

string str;

cin>>str;

int num = stoi( str );

Here, string str is converted to an integer and its value is stored in num as an integer.

Character to an Integer Conversion

To convert character to an integer we use proper casting.

Syntax:-

            int( c – ‘0’ );

where c is the character needed to be converting to an integer.

Ex:-

char c;

cin>>c;

cout<<int(c-'0')+2<<endl;

So, here c is converted to an integer so we can perform integer operation on it such as addition, subtraction etc. When c is character its not possible.

Step  by Step Approach

  • Input a number num.
  • Input the number to which we need to replace x and from which it should be replaced y.
  • Convert the number to string using to_string() function and store the string in s.
  • Now, read character by character of string s and check when u get x then add y to str otherwise s[i].
  • Directly we can’t compare the character to a number so we need to cast character to int.
  • So, final string which we got is str having replaced digits now convert str to integer using stoi() function and store its value in res.
  • Print res.

CPP Code implementation

#include<bits/stdc++.h>

 using namespace std;

   int main()
 {
     int num,x,y,i,res;
     
          cin>>num;
      
      string s,str;
      
      cout<<"Enter the digit to be replaced"<<endl;
       
           cin>>x;
       
       cout<<"Enter the digit from which it should be replaced"<<endl;
        
            cin>>y;
         
          s=to_string(num);
         
            for(i=0;i<s.length();i++)
         {
                  if(int(s[i]-'0')==x)
                {
                    str+=to_string(y);
                }
                
                     else
                 {
                     str+=s[i];
                 }
         }
         
         
         res=stoi(str);
         
           cout<<res<<endl;
     
 }

INPUT

11123

Enter the digit to be replaced
1

Enter the digit from which it should be replaced
5

OUTPUT

55523

 

Thanks For Reading !!

Please, ask your doubts and for any suggestion comment in the comment section below.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *