Convert String Builder to Integer in c# - 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);

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);

int x = Convert.ToInt32(newnum.ToString());

int x = int.parse(newnum.tostring());

Related

How to better cast a char to int keeping the number value and not the ASCII value? [duplicate]

This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 3 years ago.
I have just wrote a code(c#) for my sample exam in C# basics study.
Еven though I was able to write it correctly and receive all points, I am not quite satisfied with the way I have used to cast the char ASCII value to the desired int value.
I am asking for a better way to express the following code:
using System;
namespace MultiplyTable
{
class Program
{
static void Main(string[] args)
{
//Input:
string inputNumber = Console.ReadLine();
//Logic:
int firstNumber = 0;
int secondNumber = 0;
int thirdNumber = 0;
for (int i = 0; i < inputNumber.Length; i++)
{
firstNumber = inputNumber[0] - 48;
secondNumber = inputNumber[1] - 48;
thirdNumber = inputNumber[2] - 48;
}
for (int p = 1; p <= thirdNumber; p++)
{
for (int j = 1; j <= secondNumber; j++)
{
for (int k = 1; k <= firstNumber; k++)
{
Console.WriteLine($"{p} * {j} * {k} = {p * j * k};");
}
}
}
}
}
}
The input is an integer three-digit number in the range [111… 999].
I have used string instead of int, to quicker read and store all char values.
The issue here is that when I have the char let's say '3' I need to use the int value of '3' and not the ASCII Dec value of 51.
As I had a limited time to write this code I succeeded to resolve it by subtracting 48 as you can see in the code provided.
What is the correct/more advanced way to do this exercise ?
Thank you in advance!
Substracting foo's ASCII value from 0's ASCII value will give you number.
char foo = '2';
int bar = foo - '0';
Or you can just simply convert char to string and then convert to int:
int bar = int.Parse(foo.ToString());

Converting a string into BigInteger

I have the following code that creates a very big number (BigInteger) which is converted then into a string.
// It's a console application.
BigInteger bi = 2;
for (int i = 0; i < 1234; i++)
{
bi *= 2;
}
string myBigIntegerNumber = bi.ToString();
Console.WriteLine(myBigIntegerNumber);
I know that for converting to int we can use Convert.ToInt32 and converting to long we use Convert.ToInt64, but what's about converting to BigInteger?
How can I convert a string (that represents a very very long number) to BigInteger?
Use BigInteger.Parse() method.
Converts the string representation of a number in a specified style to
its BigInteger equivalent.
BigInteger bi = 2;
for(int i = 0; i < 1234; i++)
{
bi *= 2;
}
var myBigIntegerNumber = bi.ToString();
Console.WriteLine(BigInteger.Parse(myBigIntegerNumber));
Also you can check BigInteger.TryParse() method with your conversation is successful or not.
Tries to convert the string representation of a number to its
BigInteger equivalent, and returns a value that indicates whether the
conversion succeeded.
Here is another approach which is faster compared to BigInteger.Parse()
public static BigInteger ToBigInteger(string value)
{
BigInteger result = 0;
for (int i = 0; i < value.Length; i++)
{
result = result * 10 + (value[i] - '0');
}
return result;
}

int[] to string c#

Hi I'm developing an client application in C# and the server is written in c++
the server uses:
inline void StrToInts(int *pInts, int Num, const char *pStr)
{
int Index = 0;
while(Num)
{
char aBuf[4] = {0,0,0,0};
for(int c = 0; c < 4 && pStr[Index]; c++, Index++)
aBuf[c] = pStr[Index];
*pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128);
pInts++;
Num--;
}
// null terminate
pInts[-1] &= 0xffffff00;
}
to convert an string to int[]
in my c# client i recieve:
int[4] { -14240, -12938, -16988, -8832 }
How do I convert the array back to an string?
I don't want to use unsafe code (e.g. pointers)
Any of my tries resulted in unreadable strings.
EDIT:
Here is one of my approch:
private string IntsToString(int[] ints)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < ints.Length; i++)
{
byte[] bytes = BitConverter.GetBytes(ints[i]);
for (int j = 0; j < bytes.Length; j++)
s.Append((char)(bytes[j] & 0x7F));
}
return s.ToString();
}
I know I need to take care of endianess but as the server is running on my local machine and the server too, I assume that this is not a problem.
My other try was to use an struct with explicit layout and same FieldOffset for integer and chars but it doesn't work, either.
Maybe try something like (using LINQ):
int[] fromServer = { -14240, -12938, -16988, -8832, };
string reconstructedStr = new string(fromServer.SelectMany(BitConverter.GetBytes).Select(b => (char)(b - 128)).ToArray());
Untested, but there's something to start from. Don't know if the subtraction of 128 is correct.
You can create a comma separated string this way:
string str = String.Join(", ", intArray.Select(x => x.ToString()).ToArray());
var ints = new[] {-14240, -12938, -16988, -8832};
var result = string.Join("-", ints.Select(i => BitConverter.ToString(BitConverter.GetBytes(i))));
Console.WriteLine(result); //60-C8-FF-FF-76-CD-FF-FF-A4-BD-FF-FF-80-DD-FF-FF
BitConverter.ToString can be replaced by something else here, depending on how you will parse string later.

Adding numbers to a string?

I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.
To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.
You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();
Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();
AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}
static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.

How get the count of an array? inC#

char[] charArray = startno.ToCharArray();
//using this arry
//i want to cheque this
int i=0;
count = 0;
while (chenum [i] != "0")
{
count++;
i++;
}
string s = "0";
string zero = "0";
for (i = 1; i <= count; i++)
{
s = s + zero;
}
will u help me to correct this code...
eg:(00001101) i need to add this no with 1.
for that i want to convert this value to int.if i convert to int the no will be(1101)+1 no will be (1102).after adding i want the answer (00001102).
how many zeros do you want?? You can use string.pad
int count = 1102;
int NumOfZeros = 10;
string s = count.ToString().PadLeft(NumOfZeros, '0');
there is also the number formatter.
count.ToString("D10");
String num = "000001101";
int item = int.Parse(num);
item++;
String output = item.ToString("D8");
You need to use String.Format("{0:00000000}", 1101);, which would be 00001101
If you are storing this number as an int (and you should) 1102 annd 00001102 are the same thing. Use string formatting later when you need to output the value with some zeros.
1102.ToString("D8") will give you the string "00001102"
Also, possible duplicates of this question: Pad with leading zeros
Try int.parseInt(startNo) instead of converting it to a char array.

Categories