I need a function that takes a String as an argument, and returns a System.Windows.Input.Key. E.G:
var x = StringToKey("enter"); // Returns Key.Enter
var y = StringToKey("a"); // Returns Key.A
Is there any way to do this other than if/else's or switch statements?
Take a look at KeyConverter, it can convert a Key to and from a string.
KeyConverter k = new KeyConverter();
Key mykey = (Key)k.ConvertFromString("Enter");
if (mykey == Key.Enter)
{
Text = "Enter Key Found";
}
Key is an enum, so you can parse it like any enum:
string str = /* name of the key */;
Key key;
if(Enum.TryParse(str, true, out key))
{
// use key
}
else
{
// str is not a valid key
}
Keep in mind that the string has to match exactly (well, almost; it's a case insensitive comparison because of that true parameter) the name of the enumeration value.
var key = Enum.Parse(typeof(Key), "Enter");
Case-insensitive option:
var key = Enum.Parse(typeof(Key), "enter", true);
Related
How can i search through a bunch of keys in a Dictionary with a for loop or something like it and see if there is any key with the same first three string values as another string. the following example isnt Code at all but it is basicly the result i whant.
Key1(3932030)
Key2(4201230)
Key3(5209872)
ArrayWithKeys(3930000,4200000,5200000)
Dictionary searchForkeys(ArrayWithKeys[i])
keyFound(3932030)
First, Get substring to search and then use it to find keys inside dictionary object.
string[] keyArray = new string[]{ "3930000", "4200000" , "5200000"};
string substringToSearch ;
foreach(string inputKey in keyArray)
{
substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;
if(dictionaryObject.Keys.Any(x => x.StartsWith(substringToSearch)))
{
// below is the key matched with inputKey
dictionaryObject.Where(x => x.Key.StartsWith(substringToSearch)).First().Value;
}
}
EDIT
Using only for loop
string substringToSearch = inputKey.Length >= 3 ? inputKey.Substring(0, 3) : inputKey;
for(int i; i < dictionaryObject.Keys.Count; i++)
{
if( dictionaryObject.ElementAt(i).Key.StartsWith(substringToSearch) )
{
// key matched with inputKey
// below is key
string keyStr = dictionaryObject.ElementAt(i).Key;
}
}
I am working on a project and for a part of it I need to compare 2 strings.
My issue comes that whenever I try to compare them I always get false (==, .Equals(), String.Equals() - they all return false, even though I have 2 completely identical strings)
Here is a part of my code.
var tagType = JObject.Parse(json).First.First.ToString();
foreach (var type in assembly.ExportedTypes)
{
var name = tagType;
var currentType = type.Name;
var a = name.Length;
var b = currentType.Length;
var result = currentType == name;
var result1 = currentType.Equals(name);
var result2 = String.Equals(name, currentType, StringComparison.CurrentCulture);
var result3 = String.Equals(name, currentType, StringComparison.InvariantCulture);
var result4 = String.Equals(name, currentType, StringComparison.Ordinal);
var result5 = String.Equals(name, currentType, StringComparison.CurrentCultureIgnoreCase);
}
Now when debugging my foreach, I eventually reach a point where name and currentType both equal the same string - "AutoIncrementTag". At that same point their lengths (a and b) are equal - 16 characters.
This is what the debug output looks like:
//name - "AutoIncrementТаg"
//currentType - "AutoIncrementTag"
//a - 16
//b - 16
// result - false
// result1 - false
// result2 - false
// result3 - false
// result4 - false
// result5 - false
And ALL of the comparisons below return false.
I even tried creating a new string out of both "name" and currenType. And nothing.
I am really stuck here. How can two identical strings (same length, so no hidden characters) return false with any kind of comparison.
The second last and third last characters are not the same.
One of the second last characters is http://www.fileformat.info/info/unicode/char/0061/index.htm and the other is http://www.fileformat.info/info/unicode/char/0430/index.htm . They look the same, but aren't actually the same.
To see it, run this program:
using System;
namespace ConsoleApplication4
{
class Program
{
static string GetEscapeSequence(char c)
{
return "\\u" + ((int)c).ToString("X4");
}
static void Main(string[] args)
{
var name = "AutoIncrementТаg";
var currentType = "AutoIncrementTag";
foreach (var character in name)
{
Console.WriteLine(GetEscapeSequence(character));
}
Console.WriteLine("second string");
foreach (var character in currentType)
{
Console.WriteLine(GetEscapeSequence(character));
}
Console.ReadLine();
}
}
}
For the two strings, also compare the byte arrays.
string string1 = "AutoIncrementТаg";
string charArray = string.Join( ",", string1.ToCharArray().Select(s => (int)s));
For "AutoIncrementTag" you should get:
65,117,116,111,73,110,99,114,101,109,101,110,116,1058,1072,103
I have one variable which contains string value like below:
var stringWithSpecialChar = "/Home%";
Sometimes this variable does not contain any value like below:
var stringWithSpecialChar = "/%";
I have to check here whether this variable contains string value or not.
Everytime string value is changing so it is not sure that i will get the same value another time.
I can't understand what is a valid value in your question, so:
Use below code if a valid value is a value of some letters or some digits:
using System.Linq;
if (str.Any(char.IsLetterOrDigit)
{
//Some codes
}
But I recommend you; for checking a valid or invalid string use Regex like this:
using System.Text.RegularExpressions;
var regex = new Regex(#"[A-Za-z]"); // You have many options here
if (regex.IsMatch(str))
{
//Some codes
}
You can do this, do a foreach loop on your variable to check if it will see a string or letter.
var stringWithSpecialChar = "/Home%";
bool blStringInput;
blStringInput = IsThisString(stringWithSpecialChar);
Method to check if it will see a string value:
public static bool IsThisString(string strInput)
{
foreach (char c in strInput)
{
if (char.IsLetter(c))
return true;
}
return false;
}
Below is a simple implementation of your problem. I have considered that anything in between / and % is a string [It might contain numbers, alphabets or special characters]. Also, I have included a check inside the function whether the string is valid or not by checking whether it starts and ends with / and % respectively.
using System;
class MainClass {
public static void Main (string[] args) {
var stringWithSpecialChar = "/Home%";
bool ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/hi%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/12#%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
}
public static bool checkIfStringIsPresent(string s){
var len = s.Length;
if(s[0]!='/' || s[len-1]!='%')
return false; // if string doesn't start and and with correct symbols, then return false
var i = 0;
for(i=1;i<len-1;i++){
return true; // something is present in between / and %, so return true
}
return false; // else return false
}
}
Output:
True
False
True
True
If you know the special characters and know they are at the begining and end of the string, Trim() could be used:
var stringWithSpecialChar = "/Home%";
var value = stringWithSpecialChar.Trim('/', '%');
if(!string.IsNullOrEmpty(value))
// Use value...
One could also use string.IsNullOrWhiteSpace(value) in the condition depending on your needs.
I have str which is a string and I want to check if the last part of string is equal to other string, below I do it manually but lets say I have an array strin[] keys = {"From", "To", ...}. If its equal I want to extract (remove) it from str and put it inside key. What is the best way to achieve that?
string key;
if(str.Substring(str.Length - 4) == "From");{
key = "From";
//Do something with key
}
else if (str.Substring(str.Length - 2) == "To") {
key = "To";
//Do something with key
}
... //There may be more string to compare with
str = str.Remove(str.Length - key.Length);
You can just use FirstOrDefault and EndsWith. This will either give you the key it ends with or null. You'll have to include the using System.Linq for this to work.
string key = keys.FirstOrDefault(k => str.EndsWith(k));
if(key != null)
{
str = str.Remove(str.Length - key.Length);
}
Use a foreach loop to iterate your keys, then EndsWith() to detect and Suc´bString to extract:
foreach(string key in keys)
{
if(str.EndsWith(key))
{
int len = str.Length - key.Length;
result = str.Substring(0, len);
break;
}
}
I´m having a string with allowed chars. I´d like that user is only able to use this chars.
My idea was to loop through the unser inputs string and compare char for char. But the problem which I have is when the first char in string allowed is "A" and the first in the users input "B" is, it gives me an error...
Totally confused right now
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < allowed.Length; i++ )
{
if (allowed[i] == read[i])
{
Console.WriteLine("Okay");
}
else
{
Console.WriteLine("Invalid char on" +index);
}
}
If you wanna check if the user input has any of not allowed characters you need a nested loop, because you wanna compare each char in the user input against the chars in the allowed:
foreach(var r in read)
{
bool isValid = false;
foreach(var c in allowed)
{
// if we found a valid char set isValid to true
if(c == r)
isValid = true;
}
// if it's still false then the current char
// doesn't match any of the allowed chars
// so it's invalid
if(!isValid)
{
Console.WriteLine("the string has invalid char(s)");
break;
}
}
Or, to simplify this you can use LINQ:
bool isInvalid = read.Any(c => !allowed.Contains(c));
If you want to know which chars are invalid, you can use Except method:
var invalidChars = read.Except(allowed);
foreach(var c in invalidChars)
{
Console.WriteLine(c);
}
You either need to search the char of user input within the allowed characters or you could use a regular expression.
Search approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = false;
for (int i = 0; i < userInput.Length; i++)
{
if (!allowed.IndexOf(userInput[i]))
{
stringIsValid = false;
break; // You can stop the loop upon the first occurance of an invalid char
}
}
Regular expression approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = Regex.IsMatch(allowed, userInput);
Please note that the regular expression approach is more flexible. If you learn about regular expressions, you will find it very powerful.
You need another loop in your first one:
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < read.Length; i++ )
{
bool isValid = false;
for (int j = 0; j < allowed.Length; j++)
{
if (read[i] == allowed[j])
{
isValid = true;
break;
}
}
if (isValid)
{
Console.WriteLine("Okay");
}else{
Console.WriteLine("Invalid char on" +index);
}
}
Right now, what you're saying is "every character in read must be exactly the same as in allowed".
What you're trying to say (I think) is "every character in read must be present somewhere in allowed" – that's what the second loop does. It looks for the character in allowed and if it finds it, sets isValid to true. Otherwise the character wasn't found and it's incorrect.
As other answers here state, you can use LINQ or (preferrably) regular expressions (regex) for things like this. I assume this is homework, or you're new to C# or programming, so I provided a basic answer to (hopefully) help you understand what's not working currently with your code.
If this should indeed be a homerwok or studying-related question, then let me recommend you put that in your question next time, for it's not forbidden to ask about homework.
The "real world" solutions we would use are of no help to you if you're trying to figure out the basics, so if we know it's about learning stuff then we'll provide answers that are more useful for you.
When using a collection to store not allowed items (instead of a plain string) it opens a whole new spectrum of LINQ expressions you can use:
public static void Main(string[] args)
{
var allowed = new List<string> { "a", "b", "c" };
var read = Console.ReadLine().Select(c => c.ToString()).ToList();
if (read.All(allowed.Contains))
{
Console.WriteLine("Okay");
}
else
{
var firstNotAllowed = read.First(a => !allowed.Contains(a));
var firstIndex = read.FindIndex(a => !allowed.Contains(a));
Console.WriteLine("Invalid char: {0}, at index: {1}", firstNotAllowed, firstIndex);
}
}