There is two variable was assigned the value of "003" and "00 3". And it was convert to byte[] as below.
Before:
myStr1 = "003"; // valid, there is no blank inserted.
myStr2 = "00 3"; // invalid, there is one blank character or multi blanks character inserted.
After converted by convert(), if there are blank characters found, the source string will be convert to byte array.
myVal1 = "3"; // valid after convert
myVal2[0] = 0; // invalid, since the source myStr2 is invalid.
myVal2[1] = 1; // same as above.
And now I need determine the source string is valid or invalid based on the converted result. I dont' know how to say the result is an byte array. Could you please give me some advice. Thanks in advance.
input string type source value as SourVal
if (ResultVal is Byte Array) // how to translate the statement to C# code?
SourVal is Invalid;
else if (ResultVal is still String type) // how to translate the statement to C# code?
SourVal is valid;
ps: I failed to try the methods of typeof() and gettype() at my practice. I don't know how to use the methods. Or there is other better method for my validation.
maybe use:
if (ResultVal is byte[]) {
// SourVal is Invalid;
} else if ( ResultVal is String ) {
//SourVal is valid;
}
Try using IsWhiteSpace
//Check the String for Blank spaces if found then don't convert
if(!str.Contains(" "))
{
//use the convert method
}
else
{
//Write Message for an Invalid String
}
Related
I have the following problem
I am using an SDK that returns values form a database.
The value i need is 4, 6, 7 but the SDK returns "\u0004","\u0006","\u0007" I was wondering if there is a way to check if it is "\u0004","\u0006","\u0007" or any way of doing this?
I Have the following code (C#):
Line_Type = Line_Type.Replace(#"\u000", "");
if (Line_Type == "4")
{
Line_Type = "4";
}
else if (Line_Type == "6")
{
Line_Type = "6";
}
else if (Line_Type == "7")
{
Line_Type = "7";
}
I have tried multiple ways to get the done but can't find a right way to get this done.
I Have google but can't find anything.
From your question I understood that SDK returns values in unicoded style.
Then you can use the following code to convert unicode values to respective decimal value.
char uniCodeValue = char.Parse(Line_Type);// '\u0004' unicode values
int decimalValue = uniCodeValue;
Console.Write(decimalValue.ToString()); // prints 4
Hope your problem got solved!!
In your replace call, "\u" is considered as an escape char. if you use double \, you get the string "\u0009";
check the difference between these two:
Console.WriteLine ("\u0009");
Console.WriteLine ("\\u0009");
the second print the string you are trying to replace with an empty string.
I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.
I have a string and I want to check if it contains any invalid filename characters. I know I could use
Path.GetInvalidFileNameChars
to get a array of invalid filename characters and loop through to see if the string contains any invalid char. But is there a easier and shorter expression? It is c#. So can anyone help?
bool containsInValidFilenameCharacters(string str) {
return str.Any(Path.GetInvalidFileNameChars().Contains)
}
Note that this is the same as doing
var invalidChars = Path.GetInvalidFileNameChars();
return str.Any(c => invalidChars.Contains(c));
But since the type signature of Contains matches up exactly with the parameter delegate type of Any we can just pass it directly and it will do an implicit conversion.
Ok, hey. I made a program for an in-game.. game. And I have it load data for a player from their own .txt on my computer. Whenever i try to command (.load) it tells me (at split[1] where it is converted to an int32) which is just a test to see if your bombs load, input string is not in correct format, heres the code:
StreamReader streemy = new StreamReader(#"c:\Usernames\" + player[m.GetInt(0)].username + ".txt");
string read = streemy.ReadToEnd();
if (!string.IsNullOrEmpty(read))
{
string[] split = read.Split('=');
player[m.GetInt(0)].bombs = Convert.ToInt32(split[1]);
Say(names[m.GetInt(0)].ToUpper() + ": You data has been loaded!");
streemy.Close();
}
else
{
Say(names[m.GetInt(0)].ToUpper() + ": Your data was empty :( Say '.save' to save your current data!");
}
.save Saves the data to the .txt, "names[m.GetInt(0)]" is their username, Say just tells them in the game the message. Thanks for your help! PS: player is a struct, which has ints like bombs.
I would suggest you to use Int32.TryParse instead of Convert.ToInt32.
So if the value is not valid integer then you can treat as 0 or no bomb.
int numberOfBombs = 0;
bool result = Int32.TryParse(value, out numberOfBombs);
now numberOfBombs would retain the actual value if there is valid integer field present otherwise it will be 0.
You must be getting a FormatException.
FormatException is thrown when the arguement is not in valid format.
I think that the value of split[1] is not a valid integer.
According to msdn.
FormatException : value does not consist of an optional sign followed by a sequence of digits (0 through 9).
Using the ToInt32(string) method is equivalent to passing value to the Int32.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.
You can call the Int32.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.
Is it possible to convert alphabetical string into int in C#? For example
string str = "xyz";
int i = Convert.ToInt32(str);
I know it throws an error on the second line, but this is what I want to do.
So how can I convert an alphabetical string to integer?
Thanks in advance
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
return b;
}
this will return each characters ascii value... its up to you what you want to do with them
To answer the literal questions that you have asked
Is it possible to convert alphabetical string into int in C#?
Simply put... no
So how can I convert an alphabetical string to integer?
You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.
You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):
int parsed;
if (!Int32.TryParse(str, out parsed))
//Do Something