I am using C# and I want to convert a string to int to verify name. For example ** or 12 is not a name. I just want to convert the string into ASCII values and then will verify the name. How do I do that?
Converting back and forth is simple:
int i = int.Parse("42");
string s = i.ToString();
If you do not know that the input string is valid, use the int.TryParse() method.
From what I understand, you want to verify that a given string represents a valid name? I'd say you should probably provide more details as to what constitutes a valid name to you, but I can take a stab at it. You could always iterate over all the characters in the string, making sure they're letters or white space:
public bool IsValidName(string theString)
{
for (int i = 0; i < theString.Length - 1; i++)
{
if (!char.IsLetter(theString[i]) && !char.IsWhiteSpace(theString[i]))
{
return false;
}
}
return true;
}
Of course names can have other legitimate characters, such as apostrophe ' so you'd have to customize this a bit, but it's a starting point from what I understand your question truly is. (Evidently, not all white space characters would qualify as acceptable either.)
There multiple ways to convert:
try
{
string num = "100";
int value;
bool isSuccess = int.TryParse(num, out value);
if(isSuccess)
{
value = value + 1;
Console.WriteLine("Value is " + value);
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
It's not clear to me what you're trying to do, but you can get the ASCII codes for a string with this code:
System.Text.Encoding.ASCII.GetBytes(str)
Related
So the issuie is that i don't undertsand why out is not compatible with the char. Because when I created a simular program but starting of the line of code where the issuie is with an int it worked out fine. The worng code is that the out gives error. Can someone please explain whats more compatible? Thanks in advance :)
string Input = TxbG.Text.ToString();
Convert(Input);
}
void Convert(string Input)
{
char Output; bool Try = char.IsUpper(Input, **out** Output);
string Return = Input.ToString();
if (Try == true)
{
Return.ToUpper();
}
else
{
Return.ToLower();
}
TxbV.Text = (Return);*emphasized text*
Char.IsUpper will check only a single character and by looking at your example you are trying to check an entire string. You can check each character one by one but not an entire string. Also the method Char.IsUpper has two overloads. One is a single character and the other is a string with the character index. So the out worked with int because it was able to recognize a method with int parameter. You can try the following code for checking the string
bool IsAllUpper(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (!Char.IsUpper(input[i]))
return false;
}
return true;
}
I am sending my poolid in hdnfield when am converting it to show me error . poolid is int32 datatype
if (ddlStaticPoolName.Visible)
{
objUserEntity.POOLNAME = Convert.ToString(ddlStaticPoolName.SelectedItem.Text);
objUserEntity.POOlID = Convert.ToInt32(ddlStaticPoolName.SelectedValue);
}
else if (lblDynamicPoolName.Visible)
{
objUserEntity.POOLNAME = Convert.ToString(lblDynamicPoolName.Text);
objUserEntity.POOlID =Convert.ToInt32(hdnDynamicPoolID.Value);
}
else
{
objUserEntity.POOLNAME = "";
objUserEntity.POOlID = 0;
}
If the string Contains numerical characters But its not Whole Number (ex: double , decimal).
objUserEntity.POOlID = Convert.ToInt32(Convert.ToDouble(ddlStaticPoolName.SelectedValue));
If the string contains double Number it Cant be directly converted to Int. If this not Solve your problem you must give an Example of ddlStaticPoolName.SelectedValue.
If the string Contains Non numerical characters. Then you should use TryParse.
int num;
Int32.TryParse(ddlStaticPoolName.SelectedValue, out num);
objUserEntity.POOlID = num;
If the string contains invalid number. TryParse will set the value of num to 0. otherwise to the value Converted from string.
If you try this solutions one of them must solve your problem. But Try First solution then go To the next solution.
This question already has answers here:
How to check first character of a string if a letter, any letter in C#
(4 answers)
Closed 8 years ago.
i need some help. I have to write a programm where you can do some calculation with matrices.
The User input should be for example: A=[1,2,3;4,5,6;7,8,9]
The user should be able to save up to 10 matrices. The user should be able to write operations like A+B or C*D
I want to check, if the first character of the users input is a letter, if not, i want to give an exception. Is there a method in c# where you can check if the first character is a letter. I want to save the letters into a string array so I can reference the name of the matrices to the int [,] which contains the matrices. Here is a snippet of my code:
int i = 0;
int[][,] ArrayContainer = new int[10][,];
int rowcount;
int columncount;
while (i < 10)
{
string input = Console.ReadLine();
string trimedinput;
if (input.Contains(" "))
{
trimedinput = input.Replace(" ", string.Empty);
}
else if (input == String.Empty)
{
break;
}
else if(!input.Contains("="))
{
Console.WriteLine("The definition of your matrix is not correct. Please type in 'help' if you need help.");
continue;
}
else
{
trimedinput = input;
}
}
Thank you for help!
you can use Char.IsLetter as shown below :-
for example :-
string str = " I am a string";
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
For more information :-
http://msdn.microsoft.com/en-us/library/system.char.isletter.aspx
Use Char.IsLetter.
bool isLetter = Char.IsLetter(str[0]);
You could use char.IsLetter():
string foo = "Hello world";
bool isLetter = char.IsLetter(foo, 0);
You could use the the method IsLetter of Char type.
For instance if you have a string called test and you want to check if it's first character is a letter, you could check it out like below:
bool isLetter = Char.IsLetter(test[0])
For further documenation, please have a look here.
I am working on a simple windows forms application that the user enters a string with delimiters and I parse the string and only get the variables out of the string.
So for example if the user enters:
2X + 5Y + z^3
I extract the values 2,5 and 3 from the "equation" and simply add them together.
This is how I get the integer values from a string.
int thirdValue
string temp;
temp = Regex.Match(variables[3], #"\d+").Value
thirdValue = int.Parse(temp);
variables is just an array of strings I use to store strings after parsing.
However, I get the following error when I run the application:
Input string was not in a correct format
Why i everyone moaning about this question and marking it down? it's incredibly easy to explain what is happening and the questioner was right to say it as he did. There is nothing wrong whatsoever.
Regex.Match(variables[3], #"\d+").Value
throws a Input string was not in a correct format.. FormatException if the string (here it's variables[3]) doesn't contain any numbers. It also does it if it can't access variables[3] within the memory stack of an Array when running as a service. I SUSPECT THIS IS A BUG The error is that the .Value is empty and the .Match failed.
Now quite honestly this is a feature masquerading as a bug if you ask me, but it's meant to be a design feature. The right way (IMHO) to have done this method would be to return a blank string. But they don't they throw a FormatException. Go figure. It is for this reason you were advised by astef to not even bother with Regex because it throws exceptions and is confusing. But he got marked down too!
The way round it is to use this simple additional method they also made
if (Regex.IsMatch(variables[3], #"\d+")){
temp = Regex.Match(variables[3], #"\d+").Value
}
If this still doesn't work for you you cannot use Regex for this. I have seen in a c# service that this doesn't work and throws incorrect errors. So I had to stop using Regex
I prefer simple and lightweight solutions without Regex:
static class Program
{
static void Main()
{
Console.WriteLine("2X + 65Y + z^3".GetNumbersFromString().Sum());
Console.ReadLine();
}
static IEnumerable<int> GetNumbersFromString(this string input)
{
StringBuilder number = new StringBuilder();
foreach (char ch in input)
{
if (char.IsDigit(ch))
number.Append(ch);
else if (number.Length > 0)
{
yield return int.Parse(number.ToString());
number.Clear();
}
}
yield return int.Parse(number.ToString());
}
}
you can change the string to char array and check if its a digit and count them up.
string temp = textBox1.Text;
char[] arra = temp.ToCharArray();
int total = 0;
foreach (char t in arra)
{
if (char.IsDigit(t))
{
total += int.Parse(t + "");
}
}
textBox1.Text = total.ToString();
This should solve your problem:
string temp;
temp = Regex.Matches(textBox1.Text, #"\d+", RegexOptions.IgnoreCase)[2].Value;
int thirdValue = int.Parse(temp);
Usually when I have need to convert currency string (like 1200,55 zł or $1,249) to decimal value I do it like this:
if (currencyString.Contains("zł)) {
decimal value = Decimal.Parse(dataToCheck.Trim(), NumberStyles.Number | NumberStyles.AllowCurrencySymbol);
}
Is there a way to check if string is currency without checking for specific currency?
If you just do the conversion (you should add | NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint as well) then if the string contains the wrong currency symbol for the current UI the parse will fail - in this case by raising an exception. It it contains no currency symbol the parse will still work.
You can therefore use TryParse to allow for this and test for failure.
If your input can be any currency you can use this version of TryParse that takes a IFormatProvider as argument with which you can specify the culture-specific parsing information about the string. So if the parse fails for the default UI culture you can loop round each of your supported cultures trying again. When you find the one that works you've got both your number and the type of currency it is (Zloty, US Dollar, Euro, Rouble etc.)
As I understand it's better to do:
decimal value = -1;
if (Decimal.TryParse(dataToCheck.Trim(), NumberStyles.Number |
NumberStyles.AllowCurrencySymbol,currentCulture, out value)
{do something}
See Jeff Atwood description about TryParse. It doesn't throw an exception and extremely faster than Parse in exception cases.
To check if a string is a currency amount that would be used for entering wages - I used this:
public bool TestIfWages(string wages)
{
Regex regex = new Regex(#"^\d*\.?\d?\d?$");
bool y = regex.IsMatch(wages);
return y;
}
You might try searching the string for what you think is a currency symbol, then looking it up in a dictionary to see if it really is a currency symbol. I would just look at the beginning of the string and the end of the string and pick out anything that's not a digit, then that's what you look up. (If there's stuff at both ends then I think you can assume it's not a currency.)
The advantage to this approach is that you only have to scan the string once, and you don't have to test separately for each currency.
Here's an example of what I had in mind, although it could probably use some refinement:
class Program
{
private static ISet<string> _currencySymbols = new HashSet<string>() { "$", "zł", "€", "£" };
private static bool StringIsCurrency(string str)
{
// Scan the beginning of the string until you get to the first digit
for (int i = 0; i < str.Length; i++)
{
if (char.IsDigit(str[i]))
{
if (i == 0)
{
break;
}
else
{
return StringIsCurrencySymbol(str.Substring(0, i).TrimEnd());
}
}
}
// Scan the end of the string until you get to the last digit
for (int i = 0, pos = str.Length - 1; i < str.Length; i++, pos--)
{
if (char.IsDigit(str[pos]))
{
if (i == 0)
{
break;
}
else
{
return StringIsCurrencySymbol(str.Substring(pos + 1, str.Length - pos - 1).TrimStart());
}
}
}
// No currency symbol found
return false;
}
private static bool StringIsCurrencySymbol(string symbol)
{
return _currencySymbols.Contains(symbol);
}
static void Main(string[] args)
{
Test("$1000.00");
Test("500 zł");
Test("987");
Test("book");
Test("20 €");
Test("99£");
}
private static void Test(string testString)
{
Console.WriteLine(testString + ": " + StringIsCurrency(testString));
}
}