. NET programming to develop common function collections

Source: Internet
Author: User
Tags empty net variables string split variable tostring trim

1, DateTime Digital type
System.DateTime currenttime=new System.DateTime ();
1.1 to take the current month and the day seconds
Currenttime=system.datetime.now;
1.2 Take as the year before last
int year =currenttime.year;
1.3 Take the current month
int month =currenttime.month;
1.4 Take the current day
int day =currenttime.day;
1.5 Take current time
int when =currenttime.hour;
1.6 Take the current score
int cent =currenttime.minute;
1.7 Take the current second
int seconds =currenttime.second;
1.8 Take the current millisecond
int millisecond =currenttime.millisecond;
(Variables available in Chinese)
2, int32.parse (variable) int32.parse ("constant")
Conversion of character to 32-digit number

3, variable. ToString ()
Character conversion to string
12345.ToString ("n"); Generate 12,345.00
12345.ToString ("C"); Generate ¥12,345.00
12345.ToString ("E"); Generate 1.234500e+004
12345.ToString ("F4"); Generate 12345.0000
12345.ToString ("X"); Generate 3039 (16 binary)
12345.ToString ("P"); Generate 1,234,500.00%


4, variable. Length Number Type
Length of string:
such as: string str= "China";
int Len = str. Length; Len is a custom variable, and STR is the variable name for the measured string.

5, System.Text.Encoding.Default.GetBytes (variable)
codewords conversion to bit code
such as: byte[] bytstr = System.Text.Encoding.Default.GetBytes (str);
Then you can get the bit length:
len = bytstr.length;

6, System.Text.StringBuilder ("")
string addition, (+ is not the same?) )
such as: System.Text.StringBuilder SB = new System.Text.StringBuilder ("");
Sb. Append ("China");
Sb. Append ("people");
Sb. Append ("Republic");

7, variable. Substring (parameter 1, parameter 2);
Intercepts a portion of the string, parameter 1 is the left starting bit, and the parameter 2 is the Intercept number.
such as: string S1 = str. Substring (0,2);

8, String user_ip=request.servervariables["REMOTE_ADDR"]. ToString ();
Take remote User IP address

9, through the proxy server to take remote user real IP address:
if (request.servervariables["Http_via"]!=null) {
String user_ip=request.servervariables["Http_x_forwarded_for"]. ToString ();
}else{
String user_ip=request.servervariables["REMOTE_ADDR"]. ToString ();
}

10, session["variable"];
Access session value;
For example, assignment: session["username"]= "little Bush";

Take value: Object objname=session["username"];
String strname=objname.tostring ();
Empty: Session.removeall ();

11, String str=request.querystring["variable"];
Transfer variables by using hyperlinks.
If a hyperlink is built on any page: <a href=edit.aspx?fbid=23> Click </a>
Value in edit.aspx page: String str=request.querystring["Fdid"];

12, Doc object. createelement ("new section named");
Create a new node for an XML document

13, the parent node. AppendChild (child nodes);
Add a new child node under the XML Document parent node

14, the parent node. RemoveChild (node);
Delete a node

15, Response
Response.Write ("string");
Response.Write (variable);
Output to the page.

Response.Redirect ("URL address");
Jumps to the page specified by the URL

16, Char. ISWHITESPCE (string variable, number of digits)--Logical type
Check whether the specified position is empty character;
Such as:
String str= "Chinese people";
Response.Write (Char. Iswhitespace (str,2)); The result is: True, the first character is 0 digits, and 2 is the third character.

17, Char. Ispunctuation (' character ')--logical type
Whether Chag is a punctuation mark
such as: Response.Write (char. Ispunctuation (' A ')); return: False

18, (int) ' character '
Turn the characters into numbers, check the code points, and note the single quotes.
Such as:
Response.Write ((int) ' in '); The result is the code in the word: 20013

19, (char) code
Turn the numbers into characters and look up the characters represented by the code.
Such as:
Response.Write ((char) 22269); Return to the word "state".

20, Trim ()
Clear a space before and after a string

21, string variables. Replace ("substring", "Replace with")
String substitution
Such as:
String str= "China";
Str=str. Replace ("Country", "central"); Change the country word to the word
Response.Write (str); The output is "central"

Another example: (This very practical)

String Str= "This is <script> script";
Str=str. Replace ("<", "<font><</font>"); Replace the left angle bracket with <font> < and </font> (or change to, but it will be restored after the XML has been saved)
Response.Write (str); Display as: "This is <script> script"

If you do not replace the,<script> will not appear, if it is a script, will run, and after the replacement, the script will not run.
The value of this code is that you can disable all HTML tags in one text, display them all, and protect your interactive site.
Concrete implementation: Add your Form submit button script with the following code:
String Strsubmit=label1. Text; Label1 is the ID of the control you want the user to submit data to.
Strsubmit=strsubmit.replace ("<", "<font><</font>");
Then save or output strsubmit.
You can also use this method to easily implement UBB code.

22, Math.max (I,J)
Take the maximum value in I and J
such as int x=math.max (5,10); X will take a value of 10

* Calculate the length of the string *

String myString = "This is a test!"; Console.WriteLine ("text is: {0}", myString) Console.WriteLine ("Text's long is: {0}", Mystring.length)

* Conversion Case *

myString = Mystring.tolower ();      Convert all characters to lowercase myString = Mystring.toupper (); Convert all characters to uppercase

* Delete before and after space *

myString = Mystring.trim ();      Delete the space before and after the string char[] TrimChars = {', ' e ', ' s '};    Ready to delete the character myString = Mystring.trim (trimChars);      Deletes all specified characters myString = Mystring.trimend ();    Remove the space after the string myString = Mystring.trimstart (); To delete a space before a string

* Add spaces *

myString = Mystring.padright (14, "");    When the string is not 14 bits long, fill the myString = mystring.padleft (14, ' ") on his right with the specified character; When the string is less than 14 bits long, fill it with the specified character on his left

* Split String *

string[] Nstrs = Mystring.split (', 3); Split by Space and return the first three strings

* Get substring *

String a = Mystring.substring (2,2); Gets two characters starting at the third bit of the mystring string because the index start bit is 0

* Replace the character in the string *

String a = Mystring.replace ("i", "O"); Replace All "I" in this string with "O"

The string in C # is actually a reading group of char variables. You can access each character in the string in the following way, but you cannot modify them.

String myString = "This is a test!"; foreach (char mychar in myString) {Console.Write ("{0}", MyChar);}

To get a read-write array of characters, you can do so.

char[] Mychars = Mystring.tochararray ();

A representation method for special characters

Because of the use of double quotes in C # to break the start and end of a string, for special characters, such as double quotes themselves, they need to be represented using auxiliary characters called escape characters.

Example: Console.WriteLine ("We want to emphasize \" a scheme \.) "); The output results are as follows: We want to emphasize "a scheme".

The presentation of other special characters is listed below. Escape characters             output character             Unicode value \ '     &NBSP ;                     '               &N Bsp             0x0027 \ "                    & nbsp     "     ,                     0x0022 \\                          \          &N Bsp                 0x005c \0                & nbsp       null                  0x0000 \n      &NBS P                 line break             &NBsp     0x000a \r                        return character   &NBSP ;               0x000d \f                  & nbsp       page break                 0X000C

In addition to this escaped method above, you can also use Unicode values directly. For example: "She\ ' dog." and "she\u0027s dog." are equivalent.

Also, because there are so many characters that you sometimes need to escape, an easy way to do this is to prefix the string with "@". This allows other special characters to be used without the escape character, except that the double quotes in the string still need to be escaped. This method is especially handy for representing paths. For example: @ "C:\WINDOWS\system32" and "C:\\Windows\\System32" are equivalent.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.