Making a textbox accept a language - c#

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;

Related

How to remove a charlist from a string

How can I remove a specific list of chars from a string?
For example I have the string Multilanguage File07 and want to remove all vowels, spaces and numbers to get the string MltlnggFl.
Is there any shorter way than using a foreach loop?
string MyLongString = "Multilanguage File07";
string MyShortString = MyLongString;
char[] charlist = new char[17]
{ 'a', 'e', 'i', 'o', 'u',
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', ' ' };
foreach (char letter in charlist)
{
MyShortString = MyShortString.Replace(letter.ToString(), "");
}
Use this code to replace a list of chars within a string:
using System.Text.RegularExpressions;
string MyLongString = "Multilanguage File07";
string MyShortString = Regex.Replace(MyLongString, "[aeiou0-9 ]", "");
Result:
Multilanguage File07 => MltlnggFl
Text from which some chars should be removed 12345 => Txtfrmwhchsmchrsshldbrmvd
Explanation of how it works:
The Regex Expression I use here, is a list of independend chars defined by the brackets []
=> [aeiou0-9 ]
The Regex.Replace() iterates through the whole string and looks at each character, if it will match one of the characters within the Regular Expression.
Every matched letter will be replaced by an empty string ("").
How about this:
var charList = new HashSet<char>(“aeiou0123456789 “);
MyLongString = new string(MyLongString.Where(c => !charList.Contains(c)).ToArray());
Try this pattern: (?|([aeyuio0-9 ]+)). Replace it with empty string and you will get your desird result.
I used branch reset (?|...) so all characters are captured into one group for easier manipulation.
Demo.
public void removeVowels()
{
string str = "MultilanguAge File07";
var chr = str.Where(c => !"aeiouAEIOU0-9 ".Contains(c)).ToList();
Console.WriteLine(string.Join("", chr));
}
1st line: creating desire string variable.
2nd line: using linq ignore vowels words [captital case,lower case, 0-9 number & space] and convert into list.
3rd line: combine chr list into one line string with the help of string.join function.
result: MltlnggFl7
Note: removeVowels function not only small case, 1-9 number and empty space but also remove capital case word from string.

C# program, array

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 { ... }

Simplest way to split a string to a char array

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();

Replacing char with hex based on text table

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

How to convert part of a char array to a string

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

Categories