what is this line meaning in C# [duplicate] - c#

This question already has answers here:
c# Ternary operator
(2 answers)
Closed 4 days ago.
im new at c# and to day i met a line that i dont understand, i hope can find the answer in here
public static void Main()
{
string output = String.Join(" ", GetAlphabet(true).Where( letter =>
letter.CompareTo("M") >= 0));
Console.WriteLine(output);
}
private static List<string> GetAlphabet(bool upper)
{
List<string> alphabet = new List<string>();
int charValue = upper ? 65 : 97;
for (int ctr = 0; ctr <= 25; ctr++)
alphabet.Add(((char)(charValue + ctr)).ToString());
return alphabet;
}```
the code i didnt understand :
int charValue = upper ? 65 : 97;
i want to know what it mean

Every character has an integer value. If you have a look at an ASCII table you see that the integer value of A is 65 and for a it's 97.
In your code that is the starting value and then you have a for loop which iterates over all 26 letters. Then this integer value will be parsed to the corresponding ASCII char with ((char)(charValue + ctr)).ToString().
So 65, 66, 67, ... will be parsed to A, B, C, ...

Related

Put numbers from string into int array [duplicate]

This question already has answers here:
Convert string to int array using LINQ [duplicate]
(6 answers)
Closed 7 years ago.
I have lines (string type) of numbers like "23 78 53 4 94 32 148 31". I need to put them into int array. Here's the lame code I wrote, but it doesn't work properly:
int currentArrayValue=0;
int currentChar=0;
for (int i = 0; i < text1.Length; i++)
{
if (text1[i] != ' ')
{
currentChar++;
continue;
}
else
{
for (int k = 1; k <=currentChar; k++)
{
if (k == 1) Array[currentArrayValue] = text1[i - currentChar];
else if (k == 2) Array[currentArrayValue] = text1[i - currentChar] * 10;
else if (k == 3) Array[currentArrayValue] = text1[i - currentChar] * 100;
}
currentArrayValue++;
}
}
It can be a one-, two- or three-digit number.
There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use TryParse:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var test = "1 2 3 x";
var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
var results = new List<int>();
foreach(var value in values)
{
int x;
if(Int32.TryParse(value, out x))
{
results.Add(x);
}
else
{
Console.WriteLine("{0} is not an integer", value);
}
}
}
}
So if you have a string as such and all the numbers are separated by spaces
string foo = "12 34 567 120 12";
All you have to do is use string.Split(' ') to break this string into an array then convert those values to int values.
int[] intArray = foo.Split(' ').Select(x => Convert.ToInt32(x)).ToArray();
string input = "23 78 53 4 94 32 148 31";
var arr = Regex.Matches(input, #"\d+").Cast<Match>().Select(m => int.Parse(m.Value)).ToArray();
Use string.Split instead. You can split on each space and get an array. From there, parse each item to an int. You can actually do it all in one line with LINQ.
int[] myInts = text1.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => int.Parse(s)).ToArray();
Non-Linq answer
const string inputVal = "23 78 53 4 94 32 148 31";
string[] splitInput = inputVal.Split(' ');
int[] inputIntArray = new int[splitInput.Length];
int counter = 0;
foreach (string split in splitInput){
inputIntArray[counter++] = int.Parse(split);
}

Finding highest value in array however with assigned numbers to characters

i have a quick question
A = 10
B = 11
C = 12
D = 13
I have an char array
"5623ADCB"
I would want to find the biggest value which is D = 13 but the program doesn't recognize D = 13 when i use a for loop to look for the biggest number. Instead it outputs the D's ascii value, how do i make ensure that everytime a D is encountered, it would be recognized as 13 and not it's ascii value?
Thanks guys for your help
functional recipe: make a map from Char to Int - use Max:
static int Map(char c)
{
return Int32.Parse (c.ToString(), System.Globalization.NumberStyles.HexNumber);
}
var max = "5623ADCB".Select (Map).Max ();
get's you 13 in this case ;)
here is a version if you are concerned with memory and performance:
static int FindMax(string s)
{
s = s.ToUpper ();
var max = 0;
for (int i = 0; i < s.Length; i++) {
var v = Map (s [i]);
if (v > max)
max = v;
}
return max;
}
static int Map(char c)
{
if (c >= '0' && c <= '9')
return (int)c - (int)'0';
if (c >= 'A' && c <= 'E')
return (int)c - (int)'A' + 10;
throw new ArgumentOutOfRangeException ();
}
btw: I have no clue why you want 14 if you want D to be 13 - if the first was a typo then you have to change the Map function above (a switch will do if you don't want to get fancy) - as your first definition was exactly the same you would assume from Hex I went with it.
Do you need to get the greater value?
var array = "5623ADCB".ToCharArray();
Console.WriteLine(array.Max());
Or, to make sure "D" gets translated to "13", transform it from hexadecimal:
var array = "5623ADCB".ToCharArray();
Console.WriteLine(Convert.ToInt32(array.Max().ToString(), 16));
Notice the Convert.ToInt32(string, int) method, which receives the numeric base to translate the string expression.

Converting an integer to an array of digits [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
I want to know if there is a way in C# to convert an integer to an array of digits so that I can perform (Mathematical) operations on each digit alone.
Example: I need the user to input an integer i.e 123, 456
then the program creates two arrays of three elements {1,2,3}, {4,5,6}.
Off the top of my head:
int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();
You could create such array (or List) avoiding string operations as follows:
int x = 123;
List<int> digits = new List<int>();
while(x > 0)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits.Add(digit);
}
digits.Reverse();
Alternative without using the List and the List.Reverse:
int x = 456;
int[] digits = new int[1 + (int)Math.Log10(x)];
for (int i = digits.Length - 1; i >= 0; i--)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits[i] = digit;
}
And one more way using ToString:
int x = 123;
int[] digits = Array.ConvertAll(x.ToString("0").ToCharArray(), ch => ch - '0');
You can use this and not convert to a string:
var digits = new List<int>();
var integer = 123456;
while (integer > 0)
{
digits.Add(integer % 10);
integer /= 10;
}
digits.Reverse();

Appending sequential characters to StringBuilder [duplicate]

This question already has answers here:
How to convert a column number (e.g. 127) into an Excel column (e.g. AA)
(60 answers)
Closed 9 years ago.
I am trying to append sequential characters: A, B, ... AA, AB, ... to the beginning a a stringbuilder type. The problem I am having is that it will append all ASCII characters and not double characters. My code looks like this:
string prefix = null;
System.Text.StringBuilder text = new System.Text.StringBuilder();
for (j = 0; j < genList.Count; j++)
{
prefix = "." + Convert.ToChart(j + 65).ToString();
text.Append(prefix + genList[j]);
}
What you really want is something that will output an integer in base-26, using the letters A through Z as digits. So 0 corresponds to A, 25 is Z, 26 is AA, etc.
const string digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string ToBase26(int i)
{
StringBuilder sb = new StringBuilder();
do
{
sb.Append(digits[i % 26]);
i /= 26;
} while (i != 0);
// The digits are backwards. Reverse them.
return new string(sb.ToString.Reverse());
}
That's not the most optimum way to do it, but it'll work.
To output A, B, C, ... AA, AB, AC ... BA, etc:
for (int i = 0; i < Count; ++i)
{
Console.WriteLine(ToBase26(i));
}

Palindrome is not working [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I check if a number is a palindrome?
Hello All i want to make program to check whether palindrome number or not when user input the number. But my work does not work at all... Can you guys help me...
class Program
{
static void Main(string[] args)
{
int i = 0, j = 0 ;
int numbers =Convert.ToInt32( Console.ReadLine());
i = numbers % 10;
do
{
j = numbers / 10;
}
while (j < 10);
if (i == j)
{
Console.WriteLine(" this is palindrome number");
}
else
{
Console.WriteLine("not a palindrome");
}
The quickest way is to reverse the string and compare it to the original. You don't really need the integer conversion.
You may want to filter or correct the user's input by stripping leading zeroes (i.e. in 010). For example : string number = Convert.ToInt32(Console.ReadLine()).ToString();
You don't have to convert it to integer.
You can check it from the string.
Take the first character and the last character compare those .
Iterate the first pointer +1 and the last pointer -1 then compare.
Continue this process upto you are in middle of the string.
First of all by converting the digits to an Int32, the number of digits a user can enter are limited.
By using the modulo operation, the i variable will contain the last digit of the entered number.
By dividing the number by 10, j should eventually contain the first digit entered. However you aren't dividing it "until j is smaller than 10", but you're dividing it "while j is smaller than 10", effectively making the contents of j depend on the number of digits entered.
Even if you would fix the while condition, this code will only check the first and last digit, making it function only for 1, 2 and 3 digit numbers.
You'll need something like this:
bool isPalindrome = true;
string s = "300212003";
for (int i = 0; i < (s.Length / 2); i++)
{
if (s[i] != s[s.Length - i - 1])
{
isPalindrome = false;
break;
}
}
Console.WriteLine(isPalindrome);
It's faster than reverting a string and comparing it, only need O(n/2) operations.
a disscussion
palindrome check
C# code to check palindrome
You can follow these links .
#include<stdio.h>
#include<math.h>
void main()
{
long int n, num, rev = 0, dig;
clrscr();
printf("\n\n\t ENTER A NUMBER...: ");
scanf("%ld", &num);
n = num;
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
if (n == rev)
printf("\n\t GIVEN NUMBER IS A PALINDROME");
else
printf("\n\t GIVEN NUMBER NOT A PALINDROME");
getch();
}
Something is palindrome when you can read it either way, so when the reverse is the same as the original.
So just reverse your input string and compare it to the original.

Categories

Resources