I am looking for a function that can check the character if it is a integer and do something is so.
char a = '1';
if (Function(a))
{
do something
}
Use System.Char.IsDigit method
If you want just the pure 0-9 digits, use
if(a>='0' && a<='9')
IsNumeric and IsDigit both return true for some characters outside the 0-9 range:
Difference between Char.IsDigit() and Char.IsNumber() in C#
Integer.TryParse works well.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The bool Char.IsDigit(char c); Method should work perfectly for this instance.
char a = '1';
if (Char.IsDigit(a))
{
//do something
}
Try using System.Char.IsDigit method.
Try Char.IsNumber. Documentation and examples can be found here
It may be better to just use a switch statement. Something like:
switch(a)
{
case '1':
//do something.
break;
case '2':
// do something else.
break;
default: // Not an integer
throw new FormatException();
break;
}
This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:
try
{
Convert.ToInt32("10")
}
catch (FormatException err)
{
// Not an integer, display some error.
}
I have to check the first to characters of a string and if the third character is numeric and do it with MyString.All(char.IsDigit):
if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
Simplest answer:
char chr = '1';
char.isDigit(chr)
Related
I Have this text Grou00dfbeerenstrau00dfe and I need to convert it to Großbeerenstraße
also Eichstu00e4tt to Eichstätt
But I don't completely understand and solve this because of these reasons:
ONLY some characters (special characters) are converted, not the whole text
Unicoded texts usually have Escape characters like \u00df instead of u00df
Could you please help me to convert correctly back to its original states?
Basically, how can I convert when there is no escape character?
NOTE: If you must know, I'm sending some special charactered strings into some system. I cannot touch this system but when I request back the same string from that system, it converts Großbeerenstraße to Grou00dfbeerenstrau00dfe and so on.
Based on David's idea of looking for u and checking if the following 4 characters are valid hex numbers, it would look something like this:
public string FixGermanUnicode(string input) {
var output = new StringBuilder();
for (var i = 0; i < input.Length; i++) {
if (i < input.Length - 4 && input[i] == 'u' && input[i + 1] == '0'
&& int.TryParse(input.Substring(i + 1, 4), NumberStyles.HexNumber, null, out var code)) {
try {
output.Append(char.ConvertFromUtf32(code));
i += 4;
} catch (ArgumentOutOfRangeException) {
//not a valid unicode character
output.Append(input[i]);
}
} else {
output.Append(input[i]);
}
}
return output.ToString();
}
Console.WriteLine(FixGermanUnicode("Grou00dfbeerenstrau00dfe"));
Really, it checks for u0 to prevent cases where the next 4 characters are valid unicode, but should not have been replaced. That will work for German at least, since all the special characters in German have unicode codes starting with 0.
This will also catch scenarios where the follow 4 digits are valid hex numbers, but the resulting hex number is not a valid unicode character.
While I completely agree with #Gabriel Luci's answer, I would like to point out a more concise implementation of the same idea (it needs the ' System.Text.RegularExpression' namespace):
readonly static string unicodePattern = #"u0[0-9a-fA-F]{3}";
public static string FixGermanUnicode(string input)
{
return Regex.Replace(input, unicodePattern, match =>
{
var digits = match.Value.Substring(1);
try
{
return char.ConvertFromUtf32(int.Parse(digits, System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();
}
catch (ArgumentOutOfRangeException)
{
//not a valid unicode character
return match.Value;
}
});
}
is there a way to check if the bytes in a byte[] is a valid string, so if it contains ASCII characters only.
if (isValidASCII(myByteArray)) {
....
}
something that I could use like the above example but with functionality.
Well, if
contains ASCII characters only
means symbols with codes within [32..127] (corresponding characters are [' '..'~']) - standard ASCII table characters with command ones excluded:
Boolean isAscii = myByteArray.All(b => b >= 32 && b <= 127)
However, a valid string being defined like that can well apper to be
"$d|1 ?;)y" // this is a valid ASCII characters based string
or alike. If you want to wrap this simple Linq into a method:
public static bool isValidASCII(IEnumerable<byte> source) {
if (null == source)
return true; // or false, or throw exception
return source.All(b => b >= 32 && b <= 127);
}
...
if (isValidASCII(myByteArray)) {
...
}
Literally answering your question:
Yes. It's not only very easy, it's trivial:
Boolean isValidAscii(Byte[] bytes) {
return true;
}
This is most likely not what you're looking for.
ASCII is a table that maps each byte to a character. By definition every byte represents a valid ASCII character.
So the question really is, what are you looking for? What is a valid ASCII character in your opinion.
Once you define that, it's easy to code:
Boolean iFindThisAValidAsciiCharacter(Char c) {
//your logic here
}
Boolean isValidAscii(Byte[] bytes) {
return bytes.forAll((Byte b) => iFindThisAValidAscciCharacter( (char)b))
}
The trick, of course, is in your definition of what you consider valid.
I advice you to take a step back, and consider why you want "valid ascii" in the first place. In this brave new world of internationalization and unicode, it sounds very unlikely that what you are trying to do is going to accomplish what you want to accomplish.
First you can convert your bytes array into string using this
System.Text.Encoding.ASCII.GetString(BytesArray);
then check if it is valid or not.
string asciiString = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(BYTEVARIABLE));
now check if the the string has some chars that have been changed to '?' if yes it wasn't ASCII only.
I have a text box in my form and I want to check if the first char is equal to something,
basically I want it to do this :
if(Textbox1.text.length(0) == "a")
{
do stuff
}
Eh, are you looking for
if (Textbox1.Text.StartsWith("a")) {
// do stuff
...
}
.length only returns an integer of length of the string.
This will compare the first char with 'a'.
if(Textbox1.text[0] == 'a')
you can do this by two ways...
one i mentioned in your question's comment
second is
if(myTextBox.Text[0] == 'B')
{
//do studd
}
try smething like this:
Textbox1.Text.StartsWith("a") ? do something : do something else;
and if it is not just about first character then try something like:
Textbox1.Text.Contains("a") ? do something : do something else;
if(textBox1.Text.Substring(0,1)=="a")
Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.
Is there any built-in .NET framework support to parse these?
No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).
In your case I would just use a switch:
double dblValue;
switch strValue
{
case "-1.#IND":
dblValue = double.Nan;
break;
case "INF":
dblValue = double.Infinity;
break;
//... other casess
default:
dblValue = double.Parse(strValue);
break;
}
NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.
If you have to parse something more special, then just
public double MyParse(string text)
{
if(text == "blablabla")
return double.NaN;
if(text.Contains("blablabla")) ...
if(text.StartsWith(...
return double.Parse(text);
}
I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.