Converting a char(or string) to key value of it - c#

I'm not sure if "key value" is correct word for it as there are few formats I believe, what im talking about is http://pastebin.com/XJVx1dB5 this is format where 88 is Z etc. I hope im clear.
I have tried many things, but convert from string function of keys converter class is the only one that is remotely close. The problem is, it converts "x" to 88 as I wanted, however it fails to convert " " or "[" because it expects "SPACE"(string) and not a single space as char I believe.
I used it like this, maybe there is another(correct?) version of using it:
((int)kc.ConvertFromString(s))
So what I want to do is to get that chars of mine to code ones. How can I achieve this ?

Try something like:
var stringValue = " ";
var intValue = (int)stringValue[0];
A string is an 'array of chars' - so waht you need to do is get the char [in this case the first one] - and convert that to an int - in this case simply by casting.
If you want to do it with the enum, then you're going to have to write a manual system to convert " " to Keys.Space .

If you review your enum Keys carefully, you will see there is no value for [.
In fact, that character (on my keyboard) is reported as Oem4.
This code works:
var c = kc.ConvertFromString("Oem4");
However,
var c = kc.ConvertFromString("[");
Cannot work because [ is not a valid member of the enum you are converting from.
What do you want to do once you have converted the string? That may help guide a better answer to your question.

Related

Double.Parse fails for "10.00" retrieved value

The screenshot sums up the problem:
I have no control over the retrieved value. It comes in with some funky format that I can't figure out and the parsing fails even though it looks totally normal. Typing the value in manually works just fine.
How can I "normalize" the retrieved value so Decimal.Parse does not fail?
For reference, here is the string that fails (copied and pasted):
"‎10.00"
First I would check your regional settings to eliminate anything as simple as a difference in expected decimal separator.
If that draws a blank then if the string 10.00 parses successfully then a string that looks like 10.00 but which fails to parse cannot actually be 10.00.
Inspect and determine the character code of each character of the string and confirm that it really is 10.00 and not some exotic Unicode that has the same appearance but which is actually different (which may also include characters which are not even visible when displayed).
You might have some kind of special character hidden in the string you are retrieving.
Try this:
Double.Parse(Regex.Replace(decimalValue, #"[^0-9.,]+", ""))
You might need to add using statement for System.Text.RegularExpressions
I would replace only the one problematic character, that is the safest option:
s = s.Replace("\u200E", "");
As Jeroen Mostert mentioned in a comment, there is a non-printed character in your decimalValue.
This is a similar question which should help you deal with that.
https://stackoverflow.com/a/15259355/7636764
Edit:
Using the the string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray()); part of the solution, but also include in || char.IsPunctuation(c) after IsDigit will get your desired result.

Parsing an array

I am in need of parsing an array or characters that is a fixed length but can have just about any combination of letter or number. My 50 digit array looks like this: NL1NAMEOFCO-B032144221111000100600000-A35499001
This array represents a vast combination of settings within our product. I need to extract all reference designators in the array. The first 3 characters represent a particular model NL1, the next 8 characters represent a company NAMEOFCO. The ‘-‘ will always be in the same location. The B (digit 13) represents some value, etc, etc. Also, some values are represented by 2 digits. Digits 20 & 21 (which store the value 22), represent some specific settings.
So by now you get the idea. I can parse the array and extract the values I need by using the following code:
String Company = ConfigCode[3].ToString() +
ConfigCode[4].ToString() +
ConfigCode[5].ToString() +
ConfigCode[6].ToString() +
ConfigCode[7].ToString() +
ConfigCode[8].ToString() +
ConfigCode[9].ToString() +
ConfigCode[10].ToString();
This works without any problems, but to me, there should be an easier way of doing this. I would have thought the following would work, but it does not.
String Company = ConfigCode[3..10].ToString();
Can someone explain to me why it doesn’t work and what would be a better way of extracting the information I need?
Thanks!
I believe that String.Substring method is what you're looking for. The signature for the overloaded method you're looking for is:
public string Substring(
int startIndex,
int length
)
The documentation for it is here: http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx
For example, your Company name would be (going by the description of a character length of 8):
string CompanyName = configCode.Substring(3, 8);
Like mentioned before, you can use the Substring extension method like so:
String Company = ConfigCode.Substring(3, 8);
The square-bracket operators for strings, like in ConfigCode[3], actually return individual chars at that specific index. And C# isn't as pretty as other programming languages where stuff like array[3..10] actually gives you a portion of an array (or in this case, a string).

Need help converting a expression in python to C#

Maybe someone in either of the camps can tell me whats going on here:
Python:
temp = int('%d%d' % (temp2, temp3)) / 10.0;
I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by 10?
C# might look like:
temp = ((int)(temp2+temp3))/10;
But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#
In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;
or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;
this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for details.
So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:
Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.
Would probably want to set up a python script and try it out, placing your own values into the variables.

custom string format puzzler

We have a requirement to display bank routing/account data that is masked with asterisks, except for the last 4 numbers. It seemed simple enough until I found this in unit testing:
string.Format("{0:****1234}",61101234)
is properly displayed as: "****1234"
but
string.Format("{0:****0052}",16000052)
is incorrectly displayed (due to the zeros??): "****1600005252""
If you use the following in C# it works correctly, but I am unable to use this because DevExpress automatically wraps it with "{0: ... }" when you set the displayformat without the curly brackets:
string.Format("****0052",16000052)
Can anyone think of a way to get this format to work properly inside curly brackets (with the full 8 digit number passed in)?
UPDATE: The string.format above is only a way of testing the problem I am trying to solve. It is not the finished code. I have to pass to DevExpress a string format inside braces in order for the routing number to be formatted correctly.
It's a shame that you haven't included the code which is building the format string. It's very odd to have the format string depend on the data in the way that it looks like you have.
I would not try to do this in a format string; instead, I'd write a method to convert the credit card number into an "obscured" string form, quite possibly just using Substring and string concatenation. For example:
public static string ObscureFirstFourCharacters(string input)
{
// TODO: Argument validation
return "****" + input.Substring(4);
}
(It's not clear what the data type of your credit card number is. If it's a numeric type and you need to convert it to a string first, you need to be careful to end up with a fixed-size string, left-padded with zeroes.)
I think you are looking for something like this:
string.Format("{0:****0000}", 16000052);
But I have not seen that with the * inline like that. Without knowing better I probably would have done:
string.Format("{0}{1}", "****", str.Substring(str.Length-4, 4);
Or even dropping the format call if I knew the length.
These approaches are worthwhile to look through: Mask out part first 12 characters of string with *?
As you are alluding to in the comments, this should also work:
string.Format("{0:****####}", 16000052);
The difference is using the 0's will display a zero if no digit is present, # will not. Should be moot in your situation.
If for some reason you want to print the literal zeros, use this:
string.Format("{0:****\0\052}", 16000052);
But note that this is not doing anything with your input at all.

c# string analysis

I have a string for example like " :)text :)text:) :-) word :-( " i need append it in textbox(or somewhere else), with condition:
Instead of ':)' ,':-(', etc. need to call function which enter specific symbol
I thinck exists solution with Finite-state machine, but how implement it don't know. Waiting for advises.
update: " :)text :)text:) :-) word :-( " => when we meet ':)' wec all functions Smile(":)") and it display image on the textbox
update: i like idea with delegates and Regex.Replace. Can i when meet ':)' send to the delegate parameter ':)' and when meet ':(' other parameter.
update: Found solution with converting to char and comparing every symbol to ':)' if is equal call smile(':)')
You can use Regex.Replace with delegate where you can process matched input or you can simply use string.Replace method.
Updated:
you can do something like this:
string text = "aaa :) bbb :( ccc";
string replaced = Regex.Replace(text, #":\)|:\(", match => match.Value == ":)" ? "case1" : "case2");
replaced variable will have "aaa case1 bbb case2 ccc" value after execution.
It seems that you want to replace portions of the string with those symbols, right? No need to build that yourself, just use string.Replace. Something like this:
string text = " :)text :)text:) :-) word :-( ";
text = text.Replace(":)", "☺").Replace(":(", "☹"); // similar for others
textbox.Text += text;
Note that this is not the most efficient code ever produced, but if this is for something like a chat program, you'll probably never know the difference.
You could just create a dictionary with these specific characters as the key and pull the value.

Categories