I am trying to do string manipulation. Here's my C# code :
static void Main(string[] args)
{
string input;
string output;
int length;
Console.WriteLine("input = ");
input = Console.ReadLine();
length = input.Length;
if ((input != "") || (length != 0))
{
Random randem = new Random();
int i = -1; //because I do not want the first number to be replaced by the random number
char[] characters = input.ToCharArray();
while (i < length)
{
int num = randem.Next(0, 9);
char num1 = Convert.ToChar(num);
i = i + 2; //so that every next character will be replaced by random number.. :D
characters[i] = num1; //*error* here
}
output = new string(characters);
Console.WriteLine(output);
}
For example:
User input : "i_love_to_eat_fish"
Desired output : "i2l4v1_9o5e8t7f8s2"
notice that the only unchanged character in
the char[] characters is : "i l v _ o e t f s". (desired output from the program)
I've already tried using this code, but still,
keep getting error at characters[i] = num1;
Am I on the right track?
I'm guessing the error you get is IndexOutOfRangeException this is because of the i = i + 2;. The while makes sure that i is less than length, but then adding 2 could result in it being more. Just add a check that it isn't beyond the length.
i = i + 2;
if(i < length)
characters[i] = num1;
Or just change to a for loop.
Random randem = new Random();
char[] characters = input.ToCharArray();
for(int i = 1; i < length; i += 2)
{
int num = randem.Next(1, 10); // max value is exclusive
char num1 = num.ToString()[0];
characters[i] = num1;
}
output = new string(characters);
Console.WriteLine(output);
Also as Shar1er80 points out you're currently converting the digit to the char that has the same ASCII value, and not the the actual characters that represent the digit. The digits 0-9 are represented by the the values 48-57. You can change the call to Random.Next to be:
int num = randem.Next(48, 58); // The upper bound is exclusive, not inclusive
char num1 = (char)num;
Or as Shar1er80 does it
int num = randem.Next(0,10) // Assumming you want digits 0-9
char num1 = num.ToString[0];
Also note that the max value for Random.Next is exclusive, so if you want to include the possibility of using a 9 you have to use an upper bound that is 1 greater than the greatest value you want.
Whenever you reach i = 17 you add 2 to i . That makes i = 19 with length of input equal to 18 that causes out of range exception.
The error you are getting is IndexOutOfTheRangeException, which explains everthing in itself.
It means that index you are feeding to array in the loop is going beyond its length-1 (as arrays have 0-based indexing)
So when you do i+2, you need to check if i+2 is not exceeding i.length-1 at any point of time; which does in your loop.
In general just check if you are supplying indexes between 0 and Array.Length-1
its because you start at index -1, and characters doesn't contain an index of -1.
EDIT: Sorry no the corrct answer is it must be while(i < length - 2)
Change this line
char num1 = Convert.ToChar(num);
To
char num1 = num.ToString()[0];
Then... Put
characters[i] = num1;
In an if block
if (i < length)
characters[i] = num1;
Related
I want to use the number 25 then swap the two digits (the 2 and the 5) and then compare the swapped number (52) to the first number (25). If the swapped number is bigger I get a true and if the swapped number is smaller than the first number I get a false.
Example of what I want:
Input:
25
Output:
True //Because 25 reversed is 52, so it´s bigger
This is what I've tried:
int firstdigit = num / 10;
int secondigit = num % 10;
string res = secondigit + firstdigit.ToString();
if(res > num)
{
return true;
}
return false;
The problem now is that the "if" is not working anymore because res is a string and num is an int, but when I make res an int then I cant add the first digit and second digit because it's obviously different if I do 5 + 2 with ints (7) or 5 + 2 with strings (52).
You need to construct the reversed int value and compare against that:
int firstdigit = num / 10;
int secondigit = num % 10;
int reversed = firstdigit + seconddigit * 10;
if (reversed > num)
...
If you look at the code above, you should see that it's just reversing the logic that you used to extract the first and second digits.
Nice solution.
Maybe that's enough for you
int firstdigit = num / 10;
int secondigit = num % 10;
if(secondigit > firstdigit)
{
return true;
}
return false;
My end goal is to take a number like 29, pull it apart and then add the two integers that result. So, if the number is 29, for example, the answer would be 2 + 9 = 11.
When I'm debugging, I can see that those values are being held, but it appears that other values are also being incorrect in this case 50, 57. So, my answer is 107. I have no idea where these values are coming from and I don't know where to begin to fix it.
My code is:
class Program
{
static void Main(string[] args)
{
int a = 29;
int answer = addTwoDigits(a);
Console.ReadLine();
}
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + a[i];
}
return total;
}
}
As mentioned the issue with your code is that characters have a ASCII code value when you cast to int which doesn't match with the various numerical digits. Instead of messing with strings and characters just use good old math instead.
public static int AddDigits(int n)
{
int total = 0;
while(n>0)
{
total += n % 10;
n /= 10;
}
return total;
}
Modulo by 10 will result in the least significant digit and because integer division truncates n /= 10 will truncate the least significant digit and eventually become 0 when you run out of digits.
Your code is actually additioning the decimal value of the char.
Take a look at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
Decimal value of 2 and 9 are 50 and 57 respectively. You need to convert the char into a int before doing your addition.
int val = (int)Char.GetNumericValue(a[i]);
Try this:
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + (int)Char.GetNumericValue(a[i]);
}
return total;
}
Converted number to char always returns ASCII code.. So you can use GetNumericValue() method for getting value instead of ASCII code
Just for fun, I thought I'd see if I could do it in one line using LINQ and here it is:
public static int AddWithLinq(int n)
{
return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}
I don't think it would be particularly "clean" code, but it may be educational at best!
You should you int.TryParse
int num;
if (int.TryParse(a[i].ToString(), out num))
{
total += num;
}
Your problem is that you're adding char values. Remember that the char is an integer value that represents a character in ASCII. When you are adding a[i] to total value, you're adding the int value that represents that char, the compiler automatic cast it.
The problem is in this code line:
total = total + a[i];
The code above is equal to this code line:
total += (int)a[i];
// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.
To solve your problem, you must change that line by this:
total = (int)Char.GetNumericValue(a[i]);
// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.
You can see this answer to see how to convert a numeric value
from char to int.
At this page you can see the ASCII table of values.
public static int addTwoDigits(int n)
{
string number = n.ToString()
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total += Convert.ToInt32(number[i].ToString());
}
return total;
}
You don't need to convert the number to a string to find the digits. #juharr already explained how you can calculate the digits and the total in a loop. The following is a recursive version :
int addDigit(int total,int n)
{
return (n<10) ? total + n
: addDigit(total += n % 10,n /= 10);
}
Which can be called with addDigit(0,234233433)and returns 27. If n is less than 10, we are counting the last digit. Otherwise extract the digit and add it to the total then divide by 10 and repeat.
One could get clever and use currying to get rid of the initial total :
int addDigits(int i)=>addDigit(0,i);
addDigits(234233433) also returns 27;
If the number is already a string, one could take advantage of the fact that a string can be treated as a Char array, and chars can be converted to ints implicitly :
var total = "234233433".Sum(c=>c-'0');
This can handle arbitrarily large strings, as long as the total doesn't exceed int.MaxValue, eg:
"99999999999999999999".Sum(x=>x-'0'); // 20 9s returns 180
Unless the number is already in string form though, this isn't efficient nor does it verify that the contents are an actual number.
I try to write program that check the ratio between odd and even
digits in a given number. I've had some problems with this code:
static void Main(string[] args)
{
int countEven = 0 ;
int countOdd = 0 ;
Console.WriteLine("insert a number");
int num = int.Parse(Console.ReadLine());
int length = num.GetLength;
for (int i = 0;i<length ; i++)
{
if((num/10)%2) == 0)
int countEven++;
}
}
any ideas?
The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:
int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
if ((int.Parse(inputString[i].ToString()) % 2) == 0)
countEven++;
else
countOdd++;
}
Linq approach
Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);
Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.
int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
int m = a % 10;
switch(m % 2)
{
case 0:
evenCounter++;
break;
default: // case 1:
oddCounter++;
break;
}
//bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );
Online example
Made a small change to your code and it works perfectly
int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
{
countEven++;
}
else
{
countOdd++;
}
}
Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();
What I do is get each number as a a character in an array char[] and I loop through this array and check if its even or not.
If the Input number is a 32-bit integer (user pick the length of the number)
if asked:
The number of even digits in the input number
Product of odd digits in the input number
The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0; pOd = 0; s = 0;
for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
arn[i] = broj % 10; //using the mod we put the last digit into a declared array
if (arn[i] % 2 == 0) { // then check, is current digit even or odd
cEv++; // count even digits
} else { // or odd
if (pOd == 0) pOd++; // avoid product with zero
pOd *= arn [i]; // and multiply odd digits
}
num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
s += arn [i]; // sum of all digits
}
// and at last showing it in labels...
label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}
All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
});
// Continue with code
}
EDIT:
You could also do this with a helper (local) function within the method body:
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
// Alternative method:
IsEven(b) ? evenChars++ : oddChars++;
});
// Continue with code
bool IsEven(byte b) => b % 2 == 0;
}
Why am I using a byte?
Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM.
Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected.
An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).
Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.
And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.
static void Main(string[] args)
{
int num = 382;
int output = 0;
char[] nlst = num.ToString().ToCharArray();
for (int i = 0; i < nlst.Length; i++)
{
output += nlst[i];
}
Console.WriteLine(output);
Console.ReadLine();
}
The output result is 157, Actually it should be 13.With Dedbugging I found the 3 elements of char[] nlst like this :
[0]51'3', [1]56'8', [2]50'2'
Why? What's the meaning of 51,56,50?
You're assuming that the char value of '0' is 0. It is not; it is in fact the UTF16 value of '0' which is 48.
So you are adding together the UTF16 values of the characters '3', '8' and '2', i.e. 51, 56 and 50.
Note that if your aim is to add together all the digits of an integer, the best approach is to avoid converting to a string completely, like so:
int num = 382;
// Compute the sum of digits of num
int total = 0;
while (num > 0)
{
total += num%10;
num /= 10;
}
Console.WriteLine(total);
However if you just want to know how to get your version working, just subtract '0' from each character before adding the codes together. That will convert '0' to 0, '1' to 1, etc:
for (int i = 0; i < nlst.Length; i++)
{
output += nlst[i] - '0'; // Subtract '0' here.
}
Those are the Unicode values for '3', '8' and '2' respectively.
To convert an Unicode value (eg. 51) to the integer representation of the character represented by the Unicode value (eg. 3), use the Convert.ToInt32(char) method.
Those numbers are the char codes of the numbers. If you just want to add up the value of each Digit, you can subtract 48 from each char value to turn it into ist number value
for (int i = 0; i < nlst.Length; i++)
{
output += nlst[i] - 48;
}
Your output variable is defined as an integer. If you add (+=) a char to an integer, it's unicode value will be added to the output variable.
static void Main(string[] args)
{
int num = 382;
int output = 0;
char[] nlst = num.ToString().ToCharArray();
for (int i = 0; i < nlst.Length; i++)
{
output += Convert.ToInt32(nlst[i]);
}
Console.WriteLine(output);
Console.ReadLine();
}
You need to convert the char back to its numeric value.
Try this:
output += Convert.ToInt32(Char.GetNumericValue(nlst[i]));
[EDITED]
Char is unicode 16 (https://msdn.microsoft.com/en-us/library/x9h8tsay.aspx). You can use int.Parse
static void Main(string[] args)
{
int num = 382;
int output = 0;
char[] nlst = num.ToString().ToCharArray();
for (int i = 0; i < nlst.Length; i++)
{
output += int.Parse(nlst[i].ToString());
}
Console.WriteLine(output);
Console.ReadLine();
}
The correct solution is
output += Convert.ToInt32(nlst[i]) - '0';
or briefly
output += nlst[i] - '0';
or, as an alternative
output += Convert.ToInt32(Convert.ToString(nlst[i]));
Please note: As well as C++, C# Convert.ToInt32 converts chars to basic Unicode (i.e. good old Ascii).
I have a integer of 10 digits. I need to get the 7th digit of that integer.
I have found a mathematical solution to get the first digit of an integer.
var myDigit = 2345346792;
var firstDigit = Math.Abs(myDigit);
while (firstDigit >= 10)
{
firstDigit /= 10;
}
How can I get the seventh digit from myDigit? I am trying to avoid casting to string and doing a substring. I would like to see the mathemathical version of getting the seventh digit.
Anyone?
var seventh_digit = ( myDigit/1000000 ) % 10;
int getSeventhDigit(int number)
{
while(number >= 10000000)
number /= 10;
return number % 10;
}
This will take the last digit of numbers with 7 or less digits.
For numbers with 8 or more digits, it will divide by 10 until the number is 7 digits long, then take the last digit.
Mathematical solution without while loops:
int myDigit = 2345346792;
var seventh = (myDigit / 1000000) % 10;
//result should be 5, your seventh digit from the right
More generally, you can create a (zero-based) array from the digits:
uint myDigit = 2345346792;
int[] digits = new int[10];
for (int i = 9; i >= 0; i--)
{
digits[i] = (int)(myDigit % 10);
myDigit /= 10;
}
That should be useful for whatever manipulation you wish to do.
var nthDigit = (int)((number / Math.Pow(10, nth - 1)) % 10);
Where nth is n-th digit of the number.
Assuming that the "zeroth digit" is the least significant digit, this should do you:
public static int nthDigit( int value , int n )
{
if ( n < 0 ) throw new ArgumentException();
if ( value < 0 ) throw new ArgumentException() ;
while ( n-- > 0 )
{
value /= 10 ;
}
int digit = value % 10 ;
return digit ;
}
Something like this (C code, but should be readily portable):
if (n < 1000000)
return 0; // no 7th digit
while (n > 9999999)
n /= 10; // now in the range [1,000,000..9,999,999]
return n % 10;
This may seem outdated, but I wanted to get specific digits from a string of numbers and most of these solutions (and others I found) were lacking. So...I decided a workaround and converted the number to a string and then pulled the characters of the string, converting them back to an int. I know this isn't very efficient, but for small projects I don't concern myself with efficiency.
For my task, I was specifically working with phone numbers, so here is my code:
long number = 5559876543;
string s = "" + number;
int areaCode = int.Parse(s.Substring(0, 3));
int prefix = int.Parse(s.Substring(3, 3));
int suffix = int.Parse(s.Substring(6, 4));
I hope this helps anyone looking for a similar solution.
public static int GetNthDigit(this int value, int digits)
{
double mult = Math.Pow(10.0, digits);
if (value >= mult)
{
while(value >= mult)
value /= 10;
return value % 10;
}
else
{
throw new ArgumentOutOfRangeException("Digits greater than value");
}
}