Convert letter from textBox to an integer - c#

How do I convert alphabet letter from textBox to an integer?
For example, if the user inputs "B" in the textBox, I am trying to convert B to the number 1
string a = textBox1.Text
int number = 1;
number = int.Parsed (a);
messageBox.Show(number.ToString());

Your first task is to capture only the first character from the input:
string str = textBox1.Text;
char chr = str[0]; // get first character
Now the character can be directly converted to an integer, for example:
int number = (int)chr;
However, the character 'A' is actually represented by the number 65, 'B' 66, and so on (see ASCII), so you'll have to subtract that from your input to get the intended value:
int value = number - 65;
Or if you prefer:
int value = number - (int)'A';
Now you might want to normalize input so a character 'a' will be treated as 'A', so in the end it would look a bit like this:
string str = textBox1.Text.ToUpperCase();
char chr = str[0];
int number = (int)chr;
int value = number - 65;
MessageBox.Show(value.ToString());

Related

How to convert binary back to normal string?

So I have this:
char x = 'a';
int number = (int)x;
textBox.Text = number.ToString(); // actual "97", wanted "a"
It will display "97" if I print it.
How can I convert this back to char 'a'?
I tried a lot of things but it always displays 97.
Convert first to char (you'll get 'a' from ascii code 97) and only then to string ("a"):
textBox.Text = ((char)number).ToString();
Same idea but with implicit ToString() which will be called by string interpolation:
textBox.Text = $"{(char)number}";
You can use System.Convert:
char x = 'a';
int number = (int)x;
char chrNumber = System.Convert.ToChar(number);
textBox.text = chrNumber.ToString();

Getting the sum of all numbers in a character array

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}
You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}
If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.

When i try find Index of char in arrray i get -1

I am trying to code a simple app to let a user type a letter, and find out which position it is in in an Array, and than replace that position with the letter k.
I don`t know how to replace a char at a specific position, and the program give strange value of -1.
Thanks for any help.
Source code:
class Program
{
static void Main(string[] args) {
Random r = new Random();
string[] d = {"a" , "b" , "c" , "d" };
string randomString= "";
for (int i= 0; i < 5; i++)
{
randomString = randomString + d[r.Next(d.Length)];
}
Console.WriteLine("Debug: Random string output: " + randomString);
char[] charArray = randomString.ToCharArray();
Console.WriteLine("Type one char of random String to find postion of it:");
string userinput = Console.ReadLine();
int pos = Array.IndexOf(charArray , userinput);
Console.WriteLine(userinput +" is at " + pos + ".");
//Something to replace a char at that position with k
// Here display modified string with "k"
Console.WriteLine(randomString);
Console.ReadLine();
/*
* Console output:
Debug: Random string output: bbccb
Type one char of random String to find postion of it:
c is at -1
*/
}
}
The problem is in this line
int pos = Array.IndexOf(charArray , userinput);
You have an array of chars but you are searching a string
Change it to
int pos = Array.IndexOf(charArray , userinput[0]);
Of course you should also check if the user types anything
Your value userinput is a string, and hence a mismatch when compared to any single character in your array. You could get the first item in the string using userinput[0], but if a user enters an empty string, then that will crash (an empty string has no valid "position 0").
Instead, try this:
int pos = Array.IndexOf(charArray , userinput.FirstOrDefault());
That will return the first character if there is any; if not, it will return a char with a value of 00, which will not match anything in your array, but also not cause the program to crash.
Oh, and one more thing: To replace a character at a specific position, just set the value for that position directly:
charArray[pos] = 'K'; // Will replace character at position pos.

How can I convert any string to an integer?

How can i convert from example "1.234.567.890 VNĐ" or any string not in a correct number format.
output: 1234567890
I try: int.Parse, convert.ToInt32 or int.tryParse, double,.... But not working.
If all you want is the integer numbers that are contained within a string, you can just loop through the string and take all numbers.
string yourString = "1.234.567.890 VNĐ";
string tmpString = String.Empty;
for (int i = 0; i < yourString.Length; i++)
{
if (char.IsDigit(yourString, i))
{
tmpString += yourString[i];
}
}
int finalInt = int.Parse(tmpString);
char.IsDigit(string, int) (see documentation) checks if the char at position i in the string is a digit (not only 0..9, but also other numbers). If that's the case, add it to your string. At the end, you have all your numbers and can cast them to int.

Convert a word into character array

How do I convert a word into a character array?
Lets say i have the word "Pneumonoultramicroscopicsilicovolcanoconiosis" yes this is a word ! I would like to take this word and assign a numerical value to it.
a = 1
b = 2
... z = 26
int alpha = 1;
int Bravo = 2;
basic code
if (testvalue == "a")
{
Debug.WriteLine("TRUE A was found in the string"); // true
FinalNumber = Alpha + FinalNumber;
Debug.WriteLine(FinalNumber);
}
if (testvalue == "b")
{
Debug.WriteLine("TRUE B was found in the string"); // true
FinalNumber = Bravo + FinalNumber;
Debug.WriteLine(FinalNumber);
}
My question is how do i get the the word "Pneumonoultramicroscopicsilicovolcanoconiosis" into a char string so that I can loop the letters one by one ?
thanks in advance
what about
char[] myArray = myString.ToCharArray();
But you don't actually need to do this if you want to iterate the string. You can simply do
for( int i = 0; i < myString.Length; i++ ){
if( myString[i] ... ){
//do what you want here
}
}
This works since the string class implements it's own indexer.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = word.ToCharArray();
Voilá!
you can use simple for loop.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
int wordCount = word.Length;
for(int wordIndex=0;wordIndex<wordCount; wordIndex++)
{
char c = word[wordIndex];
// your code
}
You can use the Linq Aggregate function to do this:
"wordsto".ToLower().Aggregate(0, (running, c) => running + c - 97);
(This particular example assumes you want to treat upper- and lower-case identically.)
The subtraction of 97 translates the ASCII value of the letters such that 'a' is zero. (Obviously subtract 96 if you want 'a' to be 1.)
you can use ToCharArray() method of string class
string strWord = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = strWord.ToCharArray();

Categories

Resources