Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String Builder to Integer in c#

I am new programmer in C# and I wanna know if there is a direct way to convert from StringBuilder to int. I have the following code. On the last line of the code I get an error.

StringBuilder newnum = new StringBuilder();
for (int i = x.Length - 1; i >= 0; i--)
{
    newnum.Append(x[i]);  
}
int x = Convert.ToInt32(newnum);
like image 383
Harkamal Avatar asked Mar 17 '26 18:03

Harkamal


2 Answers

You can solve this problem by simply converting the StringBuilder to String before passing it to the Convert.ToInt32 method;

You have three different options for converting textual data to an Integer:

1:
int i = int.Parse(sb.ToString());

2:
int i = Convert.ToInt32(sb.ToString());

3:
int i;
int.TryParse(sb.ToString(), out i);
like image 62
Transcendent Avatar answered Mar 20 '26 02:03

Transcendent


int x = Convert.ToInt32(newnum.ToString());
like image 35
AlexD Avatar answered Mar 20 '26 03:03

AlexD