This post might be more theory than code.
I was wondering if there is a (relatively) simple way to use a text table (basically an array of chars) and replace the chars in a string based on their value.
Let me elaborate.
Let's say we have this two line table:
table[0x0] = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'};
table[0x1] = new char[] {'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&'};
Each array has 16 members, 0-F in hex.
Say we have a string "hello" converted to hex (68 65 6C 6C 6F). I want to take these hex numbers, and map them to the new locations as defined in the table above.
So, "hello" would now look like this:
07 04 0B 0B 0E
I can easily convert the string into an array, but I am stuck on what to do next. I feel a foreach loop would do the trick, but it's exact contents I do not yet know.
Is there an easy way to do this? It seems like it shouldn't be too hard, but I'm not quite sure how to go about doing it.
Thank you very much for any help at all!
static readonly char[] TABLE = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&',
};
// Make a lookup dictionary of char => index in the table, for speed.
static readonly Dictionary<char, int> s_lookup = TABLE.ToDictionary(
c => c, // Key is the char itself.
c => Array.IndexOf(TABLE, c)); // Value is the index of that char.
static void Main(string[] args) {
// The test input string. Note it has no space.
string str = "hello,world.";
// For each character in the string, we lookup what its index in the
// original table was.
IEnumerable<int> indices = str.Select(c => s_lookup[c]);
// Print those numbers out, first converting them to two-digit hex values,
// and then joining them with commas in-between.
Console.WriteLine(String.Join(",", indices.Select(i => i.ToString("X02"))));
}
Output:
07,04,0B,0B,0E,1B,16,0E,11,0B,03,1D
Note that if you provide an input character that isn't in the lookup table, you're not going to notice it right away! Select returns an IEnumerable, that is lazily-evaluated only when you go to use it. At that point, if the input character is not found, the dictionary [] call will throw an exeception.
One way to make this more obvious is to call ToArray() after the Select, so you have an array of indices, and not an IEnumerable. This will force the evaluation to happen immediately:
int[] indices = str.Select(c => s_lookup[c]).ToArray();
Reference:
Array.IndexOf
Enumerable.ToDictionary
Enumerable.Select
String.Join
Related
I have a list of 9 characters which from the beginning is empty:
List<char> myList = new List<char>() { '-', '-', '-', '-', '-', '-', '-', '-', '-' };
Then a user will input a letter on a certain position, which is given. Then the list will then look like this:
{'-', 'a', '-', '-', '-', '-', '-', '-', '-'}
I now want to find the string that is created from each time a new letter is added. So if the list looks like this after a while:
{'-', 'a', '-', '-', 'b', '-', 'c', 'd', '-'}
And a user adds a letter on index 6 it will look like this:
{'-', 'a', '-', '-', 'b', 'e', 'c', 'd', '-'}
So I now want to output the string "becd".
One way I found is to loop through the list in each "direction" from where the letter is added and find when there is a '-' char and stop. Then the same in the other direction. Then I can merge the letters between the start and end index.
Is there an easier and cleaner way to do this?
One way I found is to loop through the list in each "direction" from where the letter is added and find when there is a '-' char and stop. Then the same in the other direction. Then I can merge the letters between the start and end index.
Seems reasonable to me. As a List<char> chars that might look like:
var putAt = 6;
string.Concat(chars.Skip(chars.LastIndexOf('-', putAt) + 1).TakeWhile(c => c != '-'));
LastIndexOf starts at the put char (or could be put char -1 for a tiny optimization) and seeks left looking for a '-'. LINQ then skips the chars up to/including that point and takes chars rightwards while it doesn't encounter a '-'. string.Concat makes the string
If chars was an array you could do it with a range:
new string(
chars[(Array.LastIndexOf(chars, '-', putAt) + 1)..Array.IndexOf(chars, '-', putAt)]
);
I'd expect it to be more performant, but I haven't checked - again LastIndexOf does a leftwards crawl and IndexOf does a rightwards one. This gives two indexes for the range operation that cuts a chunk of chars out of the array. String's constructor takes the new charray and makes it a string
I’m working on a data entry project(visual studio windowsform) and there are two main languages that the datas have to entered in, english and arabic, i want some fields to show errorprovider if the user enters in English language in an arabic field and vice versa, is that possible?
Thanks.
Just check if all letters in the entered text are part of the english alphabet.
string text = "abc";
char[] englishAlphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
bool english = true;
foreach (char c in text.ToLower())
if (!englishAlphabet.Contains(c))
{
english = false;
break;
}
if (english)
// Do some stuff
else
// Show error
Same for the arabic alphabet.
You can do it by yourself writing logical if condition on keystroke checking for whether entered letter is of English alphabet or not. But this is not perfect solution,it wont work for other language.
You can build a function to check for arabic characters using regex:
internal bool HasArabicCharacters(string text)
{
Regex regex = new Regex(
"^[\u0600-\u06FF]+$");
return regex.IsMatch(text);
}
Or you can build a function for english characters too using regex:
internal bool HasEnglishCharacters(string text)
{
Regex regex = new Regex(
"^[a-zA-Z0-9]*$");
return regex.IsMatch(text);
}
Source: This question
And after that you can do something like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(HasArabicCharacters(textBox1.Text) == true)
{
//have arabic chars
//delete text for example
}
else
{
//don't have arabic chars
}
}
Output:
؋ = return true;
a = return false;
ئ = return true;
I'm trying to make insult program for. I wanted to use arrays to store the entire alphabet from a to z. I have used the if statement so when the user presses the letter a something happens. And, if he presses anything but a letter, something else happens. I'm stuck now.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type any bastard letter!!!");
ConsoleKeyInfo keyInfo = Console.ReadKey();
char[] array1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
if (keyInfo.KeyChar == 'a')
{
SpeechSynthesizer synth = new SpeechSynthesizer();
Console.WriteLine("You have typed a letter");
synth.Speak("You have typed a letter");
}
else
{
SpeechSynthesizer synth = new SpeechSynthesizer();
Console.WriteLine(" ");
Console.WriteLine("did you type {0}", keyInfo.KeyChar.ToString());
synth.Speak("You have typed a bastard number you infentile pillock");
}
}
}
Without iterating, just use the following expression:
if (array1.Contains(keyInfo.KeyChar)) // a letter has been typed...
{
// ...
}
else
{
// ...
}
I assume that when you say "making the array work", you mean "I want to test if the letter typed at the beginning is in the array".
char[] array1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
if (array1.Contains(keyInfo.KeyChar))
{
// user typed a letter
}
else
{
// user typed not a letter
}
I tried to show you how to check if something is in an array in C#. But since your goal is to check if the character is a letter, there is even better : Char.IsAlpha() (documentation here) (and also IsDigit() (documentation) .
In this case you don't need your initial array at all :
if (Char.IsAlpha(keyInfo.KeyChar))
{
// character is a letter (will work for both lowercase or uppercase)
}
else if (Char.IsDigit(keyInfo.KeyChar))
{
// character is a digit
}
else
{
// char is neither a digit or a letter
}
And, finally another way that doesn't involve arrays and strictly equivalent to your initial approach (thanks #JeppeStigNielsen in comments) :
if (keyInfo.KeyChar >= 'a' && keyInfo.KeyChar <= 'z')
{
// character is a lowercase letter from English-alphabet
}
else if (keyInfo.KeyChar >= '0' && keyInfo.KeyChar <= '9')
{
// character is a digit
}
else
{
// char is neither a digit or a letter
}
This works because a char is actually the code number of the corresponding character, and codes for letters (or digits) are consecutive values. see here for the list of Unicode codes
You'll need to iterate through the array and check if there is any character that matches what the user has entered but a simple solution would be to do something like:
if (array1.Any(c => c == keyInfo.KeyChar)){ ... }
else { ... }
Is there simplest way to split the word/sentence into every single char and store into array?
Eg:
Me and you.
array = { 'M', 'e', ' ', 'a', 'n', 'd', ' ', 'y', 'o', 'u', '.' };
Well, this is pretty simple :
"Me and you".ToCharArray();
Using String.ToCharArray Method
https://msdn.microsoft.com/en-us/library/ezftk57x(v=vs.110).aspx
var chars = "Me and you.".ToCharArray();
This might be helpful
// Input string.
string value = "Me and you.";
// Use ToCharArray to convert string to array.
char[] array = value.ToCharArray();
I want to convert part of a char array to a string. What is the best way to do that.
I know I can do the following for the whole array
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
but what about just elements 2 to 4 for example?
I also know I can loop through the array and extract them, but I wondered if there was a more succinct way of doing it.
Use the String constructor overload which takes a char array, an index and a length:
String text = new String(chars, 2, 3); // Index 2-4 inclusive
You may use LINQ
char[] chars = { 'a', ' ', 's', 't', 'r', 'i', 'n', 'g' };
string str = new string(chars.Skip(2).Take(2).ToArray());
But off course string overloaded constructor is the way to go