C # string functions and string operations

Source: Internet
Author: User
Tags comparison constant current time datetime html tags numeric regular expression truncated

The string is defined by the class, as follows:

Public sealed class string: icomparable, icloneable, iconvertible, icomparable <string>, ienumerable <char>, ienumerable, iequatable <string>

Note that it is derived from the ienumerable <char> interface. If you want to get all single characters, it is easy,
List <char> chars = s. tolist ();

If you want to calculate the string, it is also very simple:

Int cn = s. count (itm => itm. equals ('{'));

If you want to reverse the string, as follows:

New string (s. reverse (). toarray ());

If you traverse the string, you can use the extended method foreach.

Now there is a requirement. For a list string, I want to replace the string that meets certain conditions and keep the string that does not meet the conditions. The problem is that the string itself cannot be modified during forach. Because msdn has the following descriptions:

A string object is called immutable (read-only) because its value cannot be modified once it has been created. methods that appear to modify a string object actually return a new string object that contains the modification.

The following code constructs two strings:
String st = "hello, world ";
St = "hello, world2 ";

Back to that question, I think a very simple method is to first construct a list <string>, then traverse the original string, modify the conditions, and add a new list, if not, add them directly. This method is simple and original, with the highest efficiency. The keyword "union" exists in linq, and the union set operation exists in SQL, so we can solve the problem as follows:

Private list <string> stringcleanup (list <string> input)
      {
Regex reg = new regex (@ "<(w +)> (w + ?) </1> ", regexoptions. singleline );

Var matchitem = (
From c in input
Where reg. ismatch (c)
Select reg. replace (c, matchevaluator)
). Union (
From c in input
Where! Reg. ismatch (c)
Select c
);

Return matchitem. tolist <string> ();
      }

Private string matchevaluator (match m)
      {
Return m. groups tutorial [2]. value;
      }

Use a regular expression for matching. If the matching matches, replace the original information with the information of the matched group 2. If not, use the original string

Compare compares the content of strings and determines whether some characters are equal based on the cultural background (location).
 
Compareordinal is the same as compare, but does not consider the cultural background.
 
Format: a string containing various values and a description of how to format each value
 
Indexof specifies the first occurrence of a given substring or character in a string.
 
Indexofany specifies the first occurrence of a character or a group of characters in a string.
 
Lastindexof is the same as indexof, but located at the last location
 
Lastindexofany and indexofany, but locate the last location
 
At the beginning of the string, padleft fills the string with the specified repeated characters
 
At the end of the string, padright fills the string with the specified repeated characters
 
Replace replaces the given character or substring with another character or substring

 

1. datetime numeric type
System. datetime currenttime = new system. datetime ();
1.1 take the current year, month, day, hour, minute, second
Currenttime = system. datetime. now;
1.2 get current year
Int year = currenttime. year;
1.3 take the current month
Int month = currenttime. month;
1.4 get the current day
Int day = currenttime. day;
1.5 Current Time
Int = currenttime. hour;
1.6 get the current score
Int = currenttime. minute;
1.7 takes the current second
Int second = currenttime. second;
1.8 takes the current millisecond
Int millisecond = currenttime. millisecond;
(The variable can be in Chinese)
2. int32.parse (variable) int32.parse ("constant ")
Convert string to 32-digit font

3. Variable. tostring ()
Convert string type
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 (hexadecimal)
12345. tostring ("p"); // Generate 1,234,500.00%


4. Variable. length numeric type
String length:
For example, string str = "China ";
Int len = str. length; // len is a custom variable, and str is the variable name of the string to be tested.

5. system. text. encoding. default. getbytes (variable)
Convert character code to bit code
For example, byte [] bytstr = system. text. encoding. default. getbytes (str );
Then we can get the bit length:
Len = bytstr. length;

6. system. text. stringbuilder ("")
String addition, (is the same as the + number ?)
For example, system. text. stringbuilder sb = new system. text. stringbuilder ("");
Sb. append ("China ");
Sb. append ("people ");
Sb. append ("Republic ");

7. Variable. substring (parameter 1, parameter 2 );
Part of the string to be truncated. Parameter 1 is the start number of digits on the left, and parameter 2 is the number of digits to be truncated.
For example, string s1 = str. substring );

8. string user_ip = request. servervariables ["remote_addr"]. tostring ();
Obtain the IP address of a remote user

9. Obtain the real IP address of the remote user through the proxy server:
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, assign a value: session ["username"] = "";

Value: object objname = session ["username"];
String strname = objname. tostring ();
Clear: session. removeall ();

11. string str = request. querystring ["variable"];
Use hyperlinks to send variables.
For example, create a hyperlink on any page: <a href = edit. asp tutorial x? Fbid = 23> Click </a>
On the edit. aspx page, set the value to string str = request. querystring ["fdid"];

12. doc object. createelement ("new node name ");
Create a new node for the xml document

13. Parent node. appendchild (child node );
Add the new child node to the xml document parent node.

14. Parent node. removechild (node );
Delete a node

15. response
Response. write ("string ");
Response. write (variable );
Output to the page.

Response. redirect ("url address ");
Jump to the page specified by the url

16. char. iswhitespce (string variable, digits) -- Logical type
Check whether the specified position contains Null characters;
For example:
String str = "Chinese people ";
Response. write (char. iswhitespace (str, 2); // The result is true. The first character is 0, and the second is the third character.

17. char. ispunctuation ('Characters') -- Logical type
Check whether a character is a punctuation mark.
For example: response. write (char. ispunctuation ('A'); // return: false

18. (int) 'characters'
Convert the character into a number and check the code. Note that it is a single quotation mark.
For example:
Response. write (int) 'in'); // the code with the result of a Chinese character: 20013

19. (char) code
Convert the number into characters and check the characters represented by the code.
For example:
Response. write (char) 22269); // return the word "country.

20. trim ()
Clear leading and trailing spaces

21. String variable. replace ("substring", "replace ")
String replacement
For example:
String str = "China ";
Str = str. replace ("country", "central"); // replace the Chinese character with the central character
Response. write (str); // The output result is "central"

Another example is: (this is very practical)

String str = "this is a <script> script ";
Str = str. replace ("<", "<font> </font> "); // replace the left angle brackets with <font> and </font> (or replace them with <, but it is estimated that after saving the xml, it will be restored again)
Response. write (str); // display as: "This is a <script> script"

If not replaced, <script> is not displayed. If it is a script, it runs. If it is replaced, the script does not run.
The value of this code is that you can invalidate and display all html tags in a text file to protect your interactive websites.
Specific Implementation: add the following code to your form submission button script:
String strsubmit = label1.text; // label1 is the control id for you to submit data.
Strsubmit = strsubmit. replace ("<", "<font> </font> ");
Then save or output strsubmit.
This method can also be used to easily implement the ubb code.

22. math. max (I, j)
Take the maximum value in I and j.
For example, int x = math. max (5, 10); // x, the value is 10.

Add a bit. 23. String comparison
Add one.

23. String comparison is generally used: if (str1 = str2) {}, but there are other methods:

(1 ),
String str1; str2
// Syntax: str1.endswith (str2); _ check whether str1 ends with str2 and returns a boolean value. For example:
If (str1.endswith (str2) {response. write ("string str1 ends with" + str2 + ");}

(2 ),
// Syntax: str1.equals (str2); _ check whether str1 is equal to str2. Return a Boolean value, which is the same as the preceding syntax.

(3 ),
// Syntax equals (str1, str2); _ checks whether str1 is equal to str2 and returns a boolean value.

24. indexof (), lastindexof ()
Search for the position where the specified character or string appears for the first time (the last time) in the string, and return the index value, for example:
Str1.indexof ("word"); // search for the index value (location) of the word in str1)
Str1.indexof ("string"); // search for the index value (location) of the first character of "string" in str1)
Str1.indexof ("string", 4th); // query the index value (location) of the first character of the "string" in str1 for 2 characters starting from str1 characters)

25. insert ()
Insert the specified character into the specified index position in the string. For example:
Str1.insert (1, "word"); insert "word" to the second character of str1. If str1 = "China", it is inserted as "Chinese country ";

26. padleft (), padright ()
Add a space or a specified char character to the left (or right) of the string so that the string reaches the specified length, for example:
<%
String str1 = "Chinese ";
Str1 = str1.padleft (10, '1'); // no second parameter is added with space
Response. write (str1); // The result is "1111111 Chinese" and the string length is 10.
%>

27. remove ()
Deletes a specified number of characters from a specified position.
String comparison is generally used: if (str1 = str2) {}, but there are other methods:

1,
String str1; str2
// Syntax: str1.endswith (str2); _ check whether str1 ends with str2 and returns a boolean value. For example:
If (str1.endswith (str2) {response. write ("string str1 ends with" + str2 + ");}

2,
// Syntax: str1.equals (str2); _ check whether str1 is equal to str2. Return a Boolean value, which is the same as the preceding syntax.

3,
// Syntax equals (str1, str2); _ checks whether str1 is equal to str2 and returns a boolean value.

Indexof ()
Searches for the position of the specified character or string that appears for the first time in the string, and returns the first index value, for example:
Str1.indexof ("word"); // search for the index value (location) of the word in str1)
Str1.indexof ("string"); // search for the index value (location) of the first character of "string" in str1)
Str1.indexof ("string", 4th); // query the index value (location) of the first character of the "string" in str1 for 2 characters starting from str1 characters)

1.9 display Chinese date -- year, month, and day
String stry = currenttime. tostring ("f"); // seconds not displayed

1.10 use Chinese date to Display _ year and month
String strym = currenttime. tostring ("y ");

1.11 retrieve Chinese date display _ month/day
String strmd = currenttime. tostring ("m ");

1.12 take the current year, month, and day in the format of 2003-9-23
String strymd = currenttime. tostring ("d ");

1.13 get the current time, format: 14: 24
String strt = currenttime. tostring ("t ");
Update:

C #. net functions and method sets (add them together)


1. datetime numeric type
System. datetime currenttime = new system. datetime ();
1.1 take the current year, month, day, hour, minute, second
Currenttime = system. datetime. now;
1.2 get current year
Int year = currenttime. year;
1.3 take the current month
Int month = currenttime. month;
1.4 get the current day
Int day = currenttime. day;
1.5 Current Time
Int = currenttime. hour;
1.6 get the current score
Int = currenttime. minute;
1.7 takes the current second
Int second = currenttime. second;
1.8 takes the current millisecond
Int millisecond = currenttime. millisecond;
(The variable can be in Chinese)

1.9 display Chinese date -- year, month, and day
String stry = currenttime. tostring ("f"); // seconds not displayed

1.10 use Chinese date to Display _ year and month
String strym = currenttime. tostring ("y ");

1.11 retrieve Chinese date display _ month/day
String strmd = currenttime. tostring ("m ");

1.12 Chinese year, month, and day
String strymd = currenttime. tostring ("d ");

1.13 get the current time, format: 14: 24
String strt = currenttime. tostring ("t ");

1.14 obtain the current time in the format of 2003-09-23t14: 46: 48
String strt = currenttime. tostring ("s ");

1.15 obtain the current time in the format of 2003-09-23 14: 48: 30z
String strt = currenttime. tostring ("u ");

1.16 The current time. Format:
String strt = currenttime. tostring ("g ");

1.17 take the current time, format: tue, 23 sep 2003 14:52:40 gmt
String strt = currenttime. tostring ("r ");

1.18 obtain the date and time of the current time n days later
Datetime newday = datetime. now. adddays (100 );

2. int32.parse (variable) int32.parse ("constant ")
Convert string to 32-digit font

3. Variable. tostring ()
Convert string 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 (hexadecimal)
12345. tostring ("p"); // Generate 1,234,500.00%


4. Variable. length numeric type
String length:
For example, string str = "China ";
Int len = str. length; // len is a custom variable, and str is the variable name of the string to be tested.

5. system. text. encoding. default. getbytes (variable)
Convert character code to bit code
For example, byte [] bytstr = system. text. encoding. default. getbytes (str );
Then we can get the bit length:
Len = bytstr. length;

6. system. text. stringbuilder ("")
String addition, (is the same as the + number ?)
For example, system. text. stringbuilder sb = new system. text. stringbuilder ("");
Sb. append ("China ");
Sb. append ("people ");
Sb. append ("Republic ");

7. Variable. substring (parameter 1, parameter 2 );
Part of the string to be truncated. Parameter 1 is the start number of digits on the left, and parameter 2 is the number of digits to be truncated.
For example, string s1 = str. substring );

8. string user_ip = request. servervariables ["remote_addr"]. tostring ();
Obtain the IP address of a remote user

9. Obtain the real IP address of the remote user through the proxy server:
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 ();

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.