How to Convert String to Integer without using any BuiltIn Functions ?

Showing Answers 1 - 9 of 9 Answers

shakeelkhan

  • Nov 26th, 2007
 

The easiest way to convert string to integer with boxing and inboxing
e.g
private string a = "10";
private int b;

try{
 b = (int)a;
}
catch{
}

  Was this answer useful?  Yes

Pattiwack

  • Nov 2nd, 2011
 

I tihnk they want to see if you can manually convert the string...

Code
  1. int nResult = 0;

  2. int nNeg = '-';

  3. int nMin = '0';

  4. int nMax = '9';

  5. bool bNegate = false;

  6.  

  7. for(int i =0; i < sStringToConvert.Length; ++i)

  8. {

  9.       int nValue = sStringToConvert[i];

  10.       if( (nValue < nMin) || (nValue > nMax) )

  11.       {

  12.             if( (nValue == nNeg) && (i == 0) )

  13.             {

  14.                   bNegate = true;

  15.                   continue;

  16.             }

  17.             break;

  18.       }

  19.       nResult = nResult * 10 + (nValue - nMin);

  20. }

  21.  

  22. if(bNegate) nResult *= -1;

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions