I am usi开发者_StackOverflow社区ng 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)
精彩评论