I have this code:
string number = "124235245423523423", number2 = "3423525232332325423";
for(i=number.length-1;i>=0;i--){
int save = Convert.ToInt32(number[i]) + Convert.ToInt32(number2[i]);
}
That is not the complete code but my question is why can't I convert and access some value at a certain index of a string as an integer? Isn't there a straight forward approach to this? I have tried some things but it didn't work out.
You're looking for int.Parse.
int save = int.Parse(number[3].ToString());
Converting a char to Int32 returns the value of that character in the current encoding.
For more information, see the MSDN documentation for Int32.Parse.
I think that this is what you are looking for. You have to access the string by the indexer value and then convert:
int yourNumber = Convert.ToInt32(number[4].ToString());
This will give you value 3
Here is one way to do it:
string number = "124235245423523423", number2 = "3423525232332325423";
for(int i=number.Length-1;i>=0;i--){
int save = int.Parse(number[i].ToString()) + int.Parse(number2[i].ToString());
Console.WriteLine(save);
}
When Convert.ToInt32() gets a char, it returns the UTF-16 encoded code unit of the value argument (read on MSDN).
On the other hand, when it gets a string, it returns the number that string contains, or throws an exception if it's not a number.
I believe the String.ToCharArray is what you're looking for:
https://msdn.microsoft.com/en-us/library/2c7h58e5(v=vs.110).aspx
I needed a value at a certain index, here's how i did it and it works wonderfully for me:
int number = (int)char.GetNumericValue(number[index])
What I actually did is that i converted the character at the index i needed into a double first through GetNumericValue method and then i converted that double into an integer.
string number = "124235245423523423", number2 = "3423525232332325423";
for(int i=number.Length-1;i>=0;i--){
int sum = int.Parse(number[i].ToString()) + int.Parse(number2[i].ToString());
Console.WriteLine(sum);
working example
Well, since number[i] is of type char you can convert it into corresponding int either by (the most general case)
int result = (int) char.GetNumericValue(number[i]);
please notice, that char.GetNumericValue returns double, it's actual for, say, '⅜' character (3/8 corrsponds to 0.375); or if you work with ['0'..'9'] range only, all you have to do is to subtract '0':
int result = number[i] - '0';
So far your code can be implemented as
// Math.Min - number.Length and number2.Length have diffrent size
// - 1 - strings are zero-based [0..Length - 1]
for (i = Math.Min(number.Length, number2.Length) - 1; i >= 0; i--) {
int save = number[i] + number2[i] - 2 * '0';
...
}
probably you want to right align both strings:
number = "124235245423523423"
+
number2 = "3423525232332325423"
------------------------------
354... ...846
in this case you have to modify for loop:
for (int i = 0; i < Math.Max(number.Length, number2.Length); ++i) {
int sum =
(i < number.Length ? number[number.Length - i - 1] : '0') +
(i < number2.Length ? number2[number2.Length - i - 1] : '0') -
2 * '0';
...
}
Related
I'm trying to get the last two digits of an int that is a minimum of 3 digits long. Here is my (rather sloppy) attempt:
char[] number = num.ToString().ToCharArray();
int firstnum;
int secondnum;
string strLastTwoDigits = "";
int intLastTwoDigits;
firstnum = number[number.ToString().Length - 1];
secondnum = number[number.ToString().Length - 2];
strLastTwoDigits = (firstnum.ToString() + secondnum.ToString());
intLastTwoDigits = int.Parse(strLastTwoDigits);
The num variable is the number I'm trying to get the last two digits of. I'm trying to turn them into strings and use the string functions to do it, probably not the way it's done. The logic to check whether it's 3 digits or more isn't included, I don't need help with that, just getting those last two digits.
Any ideas?
Do you need those two numbers as a String? Or do you plan to convert them back to a number.
Because if you want to have a number at the end, just use the modulo- operator %.
You can find an example on how to use it here: https://www.dotnetperls.com/modulo
Edit: to state the obvious: last2 = number % 100;
Just perform a modulo operation.
var intLastTwoDigits = num % 100;
You can use the modulo of that number, it should be something like
int lastTwoDigits = num % 100;
This function will divide num / 100and gives you the rest as integer.
If you need the last to digits as int, you could just use modulo:
int lasttwo = num % 100;
the modulo operator (%) will return you the remainder of the division of one integer is by another - in this case your number divided by 100 - the remainder will always be the last two digits
If you want to use strings for that, string.Substring method will help you
var numString = num.ToString();
var strLastTwoDigits = numString.Substring(numString.Length - 2, 2);
var intLastTwoDigits = int.Parse(strLastTwoDigits);
Another (and more simpler option) is to use remainder % operator for that
int intLastTwoDigits = num % 100;
You get a remainder of division into 100, because you need the 2 last digits
I have been searching around the internet for a while but haven't found what I am looking for.
Let me start with some code example:
int a = 25;
int b;
int c;
What I want to do here is I want to split the a variable and give the two values to variable b and c. The result would be int b = 2 and int c = 5, or vice versa (doesn't matter in the purpose I'm going to use this).
How can you do this?
You can use integer division and modulo for that:
int b = a / 10;
int c = a % 10;
If the variable a contains a larger number, you would first determine how many digits you want in each variable. If you for example want two digits in c, you would use 100 as the second operand in both operations.
One way you could do it is with the following code:
int input = 123845;
var digits = input.ToString().Select(x=>int.Parse(x.ToString()));
This will first of all convert your input number to a string. It then treats this string as a character array when passing to Select. It then converts the char to a string and then parses it as an int, resulting in an IEnumerable<int>.
Of note is that this won't work if your input is a negative number (it will complain about the -). It wouldn't be too hard to check for the "-" at the beginning if you wanted to though.
The other way is to continually divide by 10 getting all the digits out one by one.
public IEnumerable<int> GetDigits(int input)
{
int currentNumber = input;
List<int> digits = new List<int>();
while (currentNumber !=0)
{
digits.Add(currentNumber%10);
currentNumber = currentNumber/10;
}
digits.Reverse();
return digits;
}
This will loop through the number adding the last digit to a list as it goes. It then returns the list reversed. This does deal with negative numbers and if the input is negative all output numbers iwll be negative.
An important note is that both of these methods will deal with more than two digits input numbers.
int a = 12345;
a = Math.Abs(a);
int length = a.ToString().Length;
int[] array = new int[length];
for (int i = 0; i < length; i++)
{
array[i] = a % 10;
a /= 10;
}
I have to split a value example 44 I need the second 4. I have a way to so so now I just can figure how to make int index-able. I can make it indexable using string but I need it in int. How can I solve this issue?
Conversion that does not work
int secondDigit = num;
ld.ScaleGroup = (ScaleGroup)Convert.ChangeType(secondDigit, typeof(ScaleGroup));
int num = Convert.ToInt32(ld.ScaleGroup);
char secondDigit = num[1];//here is the issue
You can try:
int secondDigit = (int) char.GetNumericValue(num.ToString()[1]);
But a simpler option would be:
int secondDigit1 = num % 10;
If Id.ScaleGroup is a string then you can directly access its value at index 1, but remember to check the Length before accessing index.
The simpler option (involving % division) would only work for two digit numbers.
Some years back when I was still a beginner at programming, I found some code online that could generate a bruteforce-code given an offset.
So for instance, if I did GetPassword(1) it would return "a", and if I did GetPassword(2) it would return "b" etc.
Every increment of the offset would provide the next possible combination of strings. A minimum and maximum length of the "password to guess" could also be provided.
Now I have no idea where this code is, or what the algorithm is called. I want to implement one myself, since I need it for URL-enshortening purposes. A user generates a URL that I want to look somewhat long these lines: http://fablelane.com/i/abc where "abc" is the code.
You can think of the output from GetPassword as a number in a different base. For example if GetPassword can output upper and lower case alphanumeric then it is in base 62 -> 26 letters + 26 letters + 10 digits.
GetPassword must convert from base 10 to base 62 in this case. You can use a look up array to find the output characters.
You can convert from one base to another by using an algorithm such as this:
Another stackoverflow post
This is base 26 encoding end decoding:
public static string Encode(int number){
number = Math.Abs(number);
StringBuilder converted = new StringBuilder();
// Repeatedly divide the number by 26 and convert the
// remainder into the appropriate letter.
do
{
int remainder = number % 26;
converted.Insert(0, (char)(remainder + 'a'));
number = (number - remainder) / 26;
} while (number > 0);
return converted.ToString();
}
public static int Decode(string number) {
if (number == null) throw new ArgumentNullException("number");
int s = 0;
for (int i = 0; i < number.Length; i++) {
s += (number[i] - 'a');
s = i == number.Length - 1 ? s : s * 26;
}
return s;
}
I have a problem and cant find a solution. I have numbers (decimal) like 85.12343 or 100 or 1.123324. I want to format this in a way that the result is always 13 chars long including the separator.
100 --> 100.000000000
1.123324 --> 1.12332400000
I tried with toString, but failed. How could I do this?
Thanks :)
int digits = 13;
decimal d = 100433.2414242241214M;
int positive = Decimal.Truncate(d).ToString().Length;
int decimals = digits - positive - 1; //-1 for the dot
if (decimals < 0)
decimals = 0;
string dec = d.ToString("f" + decimals);
It will not remove digits from the whole part, only the fraction, when needed.
I'd go with Kobi's answer, unless it's possible you could have more than 13 digits to start with, in which case you might need to do something like this (warning: I have not even attempted to make this efficient; surely there are ways it could be optimized if necessary):
public static string ToTrimmedString(this decimal value, int numDigits)
{
// First figure out how many decimal places are to the left
// of the decimal point.
int digitsToLeft = 0;
// This should be safe since you said all inputs will be <= 100M anyway.
int temp = decimal.ToInt32(Math.Truncate(value));
while (temp > 0)
{
++digitsToLeft;
temp /= 10;
}
// Then simply display however many decimal places remain "available,"
// taking the value to the left of the decimal point and the decimal point
// itself into account. (If negative numbers are a possibility, you'd want
// to subtract another digit for negative values to allow for the '-' sign.)
return value.ToString("#." + new string('0', numDigits - digitsToLeft - 1));
}
Example inputs/output:
Input Output
---------------------------------------
100 100.000000000
1.232487 1.23248700000
1.3290435309439872321 1.32904353094
100.320148109932888473 100.320148110
0.000383849080819849081 .000383849081
0.0 .000000000000
Quick 'n' dirty:
return (value.ToString("0.#") + "0000000000000").Substring(0, 13);
string formatted = original.ToString("0.000000000000").Remove(13);
Besides simply padding the string you can do some more elaborate math to determine the number of digits:
String FormatField(Int32 fieldWidth, Decimal value) {
var integerPartDigits =
value != Decimal.Zero ? (int) Math.Log10((Double) value) + 1 : 1;
var fractionalPartDigits = Math.Max(0, fieldWidth - integerPartDigits - 1);
return value.ToString("F" + fractionalPartDigits);
}
Note that if the value is negative or has an integer part with one less digit than the field width you will not get the desired result. However, you can modify the code to accommodate these cases based on exactly how you want to format and align these numbers.
What about
string newString;
if (original.ToString().Length >= 13)
{
newString = original.ToString().Substring(13);
}
else
{
newString = original.ToString().PadRight(13, '0');
}
int noofdecimal=3;
double value=1567.9800
value.ToString("#." + new string('0', noofdecimal));
//Result=1567.980