String (not just letter) to ConsoleKey c# - c#

So i need to convert string to ConsoleKey...
Yes something like this works:
string ch = "a";
ConsoleKey ck = (ConsoleKey)Convert.ToChar(ch);
But what if the string is like "UpArrow" (the string is from ReadKey input and saved to txt file)
Please help.

You can convert a string to an enum member using Enum.Parse or Enum.TryParse.
Unfortunately the API is not generic, so you have to specify the type a few times:
ConsoleKey key1 = (ConsoleKey)Enum.Parse(typeof(ConsoleKey), "UpArrow");
The above will throw an exception if the string is not a member of the enum. To protect against that you could use:
if (Enum.TryParse("UpArrow", out ConsoleKey key2))
{
// use 'key2' in here
}

Related

What do I use to convert string into unicode

I am having an issue with this block of code.
Console.WriteLine("What is your name?");
string PlayerName = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(PlayerName);
What I'm trying to do is get the computer to read the name you input, and ask you if that is your name. Directly after I type my name though there is an exception. Convert.ToInt32 isn't what I'm supposed to use, and I guess my question is what do I put there instead.
I am new to programming and I'm not even sure if it's called unicode. Sorry.
Console.ReadLine() will return a string, no need to do any conversions:
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);
Convert.ToInt32() throw casting error if you do not pass valid integer value inside it. So, you need to check it gracefully and get interger value. For that, you can Int32.TryParse(input, out val) and get integer value.
Ex :
int value;
if(Int32.TryParse(your_input, out value))
{
// if pass condition, then your input is integer and can use accordingly
}
So, your program will be like this if you want to print integer value only :
Console.WriteLine("What is your name?");
var value = Console.ReadLine();
int intVal;
if(Int32.TryParse(value, out intVal))
{
Console.WriteLine(intVal);
}
If you want only to print what you've got from ReadLine method, you can just have :
Console.WriteLine("What is your name?");
Console.WriteLine(Console.ReadLine());
Convert.ToInt32(String) "Converts the specified string representation of a number to an equivalent 32-bit signed integer". You are getting an error because you are not typing in an integer value in your console.
Your PlayerName variable is of type string, and the return value of Console.ReadLine() is already a string, so you don't need any conversion.
If you’re dealing with Unicode characters, you might have to set proper encoding like so
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);

Casting HexNumber as character to string

I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.

c# combine code with string

i am wondering how to combine code + int/string
example.
string USERINPUT = Console.ReadLine();
Console.ForgroundColor = ConsoleColor.USERINPUT
but that does not work. how to i wonder?
For the assignment
Console.ForegroundColor = (something here);
you must assign a ConsoleColor, which is an enum.
You can parse an enum value from it's string equivalent.
Console.ForegroundColor =
(ConsoleColor)System.Enum.Parse(typeof(ConsoleColor), USERINPUT);
For details see:
Search for a string in Enum and return the Enum
Note that my code does not include error handling. If the user types in a string at the console that is not a member of ConsoleColor, you will get an error condition.

Convert alphabetic string into Integer in C#

Is it possible to convert alphabetical string into int in C#? For example
string str = "xyz";
int i = Convert.ToInt32(str);
I know it throws an error on the second line, but this is what I want to do.
So how can I convert an alphabetical string to integer?
Thanks in advance
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
return b;
}
this will return each characters ascii value... its up to you what you want to do with them
To answer the literal questions that you have asked
Is it possible to convert alphabetical string into int in C#?
Simply put... no
So how can I convert an alphabetical string to integer?
You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.
You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):
int parsed;
if (!Int32.TryParse(str, out parsed))
//Do Something

C#: Is there a way to search a string for a number without using regex?

Is there a way to check to see if a string contains any numeric digits in it without using regex? I was thinking of just splitting it into an array and running a search on that, but something tells me there is an easier way:
//pseudocode
string aString = "The number 4"
If (aString contains a number) Then enter validation loop
Else return to main
//output
"The string contains a number. Are you sure you want to continue?"
var containsdigit = somestring.Any(char.IsDigit);
You could use String.IndexOfAny as:
bool isNumeric = mystring.IndexOfAny("0123456789".ToCharArray()) > -1;
You could create an extension method for string and use a combination of LINQ and the Char.IsNumber function e.g.
public static class StringExt
{
public static bool ContainsNumber(this string str)
{
return str.Any(c => Char.IsNumber(c));
}
}
Then your logic would look like:
//pseudocodestring
string str = "The number 4";
If (aString.ContainsNumber())
enter validation

Categories

Resources