
C# string declare, convert it to int, float and datetime
1. C# string
The "string" is used to define string variables. It is an alias of "String" and is a reference type. Unlike other data types that have a range and occupy bytes, it can store a series of characters.
2. C# declare string variable
string text = "C# string";
string str,text;//The default value is null
string str = "C#",text = "C# declare string variable";
string filePath = @"G:\xq\test";//There is an escape character \ in the string, add @ in front
string filePath = "G:\\xq\\test";//There is an escape character \ in the string, add \ before the escape character
If the string is very long and one line cannot be displayed, it needs to be displayed on a new line. You can also add @ before the string, refer to string filePath.
C# declare string array:
string[] arr = { "C#", "declare", "string array" };
declare[] arr1 = new string[3]{ "C#", "string", "string array" };
declare[] arr2 = new string[]{ "C#", "string", "string array" };
3. C# string is converted to other data types
A. C# string to int(the converted character requires a number, otherwise an exception may occur)
string num = "200";
int n = int.Parse(num);//When "num" is not a number, an exception occurs
int n = DateTime.ToInt32(num);//When "num" is not a number, an exception is triggered
B. C# string to float
string text = "80";
double d = double.Parse(text);
double d1 = DateTime.ToDouble(text);
The conversion result is 80. If there are non-data characters(such as 80t) in the string, both conversion methods will throw exceptions.
C. C# string to datetime
string date = "08/24/2020";
DateTime dt = DateTime.Parse(date);//When "date" is not a date, an exception occurs
DateTime dt = DateTime.ToDateTime(date);//When "date" is not a date, an exception occurs
Converting to other data types also uses the corresponding methods of Parse() and DateTime. Refer to the above conversion examples and draw inferences.
-
Related Reading
- Javascript trim string whitespace, with removing lef
- C# convert punctuation marks to Unicode encoding
- Convert Unicode to string C#(with string to unicode)
- C# split string with \n pay attention to the problem
- C# declare datetime variable, its range and type con
- C# efficiency comparison of multiple strings concate
- Javascript convert hex to decimal, binary to hex, oc
- C# date format and examples, with binding and ToStri
- C# remove first or last character from string
- Difference between substr and substring in javascrip
- C# declare array(with values) and resize to add elem
- Javascript split usage and examples, with splitting