C # string operations

Source: Internet
Author: User
1. Extract substrings from strings
The stringbuilder class does not support substrings. Therefore, the string class must be used for extraction.
String mystring = "My name is ynn .";
// Displays "name is ynn ."
Console. writeline (mystring. substring (3 ));
// Displays "ynn"
Console. writeline (mystring. substring (11,3 ));

2. compare strings
The string class has four methods: Compare (), compareto (), compareordinal (), and equals ().
The compare () method is the static version of The compareto () method. If the "=" operator is used, the equals () method is called. The equals () method is equivalent to "=. The compareordinal () method does not compare two strings with local languages and files.
Example:
Int result;
Bool bresult;
S1 = "aaaa ";
S2 = "BBBB ";
// Compare () method
// The result value is "0", indicating equality. If it is less than zero, it indicates S1 <S2, and if it is greater than zero, it indicates S1> S2.
Result = string. Compare (S1, S2 );
Result = s1.compareto (S2 );
Result = string. compareordinal (S1, S2 );
Bresult = s1.equals (S2 );
Bresult = string. Equals (S1, S2 );
One exception is that both strings are built-in and equal, and the static method is much faster.

3. String formatting

3.1 format a number
Description of format characters and associated attributes

C and C currency formats.
In decimal format.
E, E scientific count (INDEX) format.
F and F are fixed points.
G.
N, N numeric format.
The r and r round-trip formats Ensure that the number converted to a string has the same value as the original number when being converted back to a number.
X and X hexadecimal formats.
Double val = math. Pi; console. writeline (Val. tostring (); // displays 3.14159265358979
Console. writeline (Val. tostring ("e"); // displays 3.141593e + 000
Console. writeline (Val. tostring ("F3"); // displays 3.142int val = 65535;
Console. writeline (Val. tostring ("X"); // displays FFFF
Console. writeline (Val. tostring ("X"); // displays FFFF
Single Val = 0.123f; console. writeline (Val. tostring ("p"); // displays 12.30%
Console. writeline (Val. tostring ("p1"); // displays 12.3%
By default, a space is placed between the digit and the percent sign. The customization method is as follows:
The numberformatinfo class is a member of the system. Globalization namespace. Therefore, the namespace must be imported to the program.
Single Val = 0.123f;
Object myobj = numberformatinfo. currentinfo. Clone () as numberformatinfo;
Numberformatinfo myformat = myobj as numberformatinfo;
Myformat. percentpositivepattern = 1;
Console. writeline (Val. tostring ("P", myformat); // displays 12.30%;
Console. writeline (Val. tostring ("p1", myformat); // displays 12.3%;
Formatting is flexible. The following example demonstrates a meaningless currency structure:
Double val = 1234567.89;
Int [] groupsize = {2, 1, 3 };
Object myobj = numberformatinfo. currentinfo. Clone ();
Numberformatinfo mycurrency = myobj as numberformatinfo;
Mycurrency. currencysymbol = "#"; // symbol
Mycurrency. currencydecimalseparator = ":"; // decimal point
Mycurrency. currencygroupseparator = "_"; // delimiter
Mycurrency. currencygroupsizes = groupsize; // output #1_234_5_67: 89
Console. writeline (Val. tostring ("C", mycurrency ));

3.2 format a date
The output format depends on the cultural settings of the user's computer.
Using system;
Using system. Globalization;
Public class mainclass
{
Public static void main (string [] ARGs)
{
Datetime dt = datetime. now;
String [] format = {"D", "D", "F", "F", "g", "g", "M", "r ", "S", "T", "T", "U", "U", "Y", "dddd, Mmmm dd YYYY", "DDD, mmm D "" '"YY", "dddd, Mmmm dd", "m/YY", "DD-mm-yy ",};
String date;
For (INT I = 0; I <format. length; I ++)
{
Date = DT. tostring (Format [I], datetimeformatinfo. invariantinfo );
Console. writeline (string. Concat (Format [I], ":", date ));
}
}
}
D: 07/11/2004 <===== output
D: Sunday, 11 July 2004
F: Sunday, 11 July 2004
F: Sunday, 11 July 2004 10:52:36
G: 07/11/2004
G: 07/11/2004 10:52:36
M: July 11
R: Sun, 11 Jul 2004 10:52:36 GMT
S: 2004-07-11t10: 52: 36
T: 10: 52
T: 10: 52: 36
U: 2004-07-11 10: 52: 36z
U: Sunday, 11 July 2004 02:52:36
Y: 2004 July
Dddd, Mmmm dd yyyy: Sunday, July 11 2004
DDD, mmm D "'" YY: Sun, Jul 11' 04
Dddd, Mmmm DD: Sunday, July 11
M/YY: 7/04
DD-mm-yy: 11-07-04

3.3 format Enumeration
Enum classmen
{
Ynn = 1,
Yly = 2,
CSS = 3,
C ++ = 4
}
Obtain the enumerated string information as follows:
Classmen myclassmen = classmen. yly;
Console. writeline (myclassmen. tostring (); // displays yly
Console. writeline (myclassmen. tostring ("D"); // displays 2
The following information is obtained from the system enumeration:
Dayofweek day = dayofweek. Friday;
// Displays "Day is Friday"
Console. writeline (string. Format ("Day is {0: g}", day ));
Format the string "G" to display the enumeration as a string.

Several common functions are introduced:

Compare (str1, str2) -- compare the size of two strings str1 and str2. If it is greater than the return positive number, it is equal to the return 0. If it is less than the return negative number!

Indexof -- locate the position where a given string appears for the first time in a string
Padleft and padright -- fill the string with the specified character at the beginning and end of the string
Tolower and toupper convert strings to lowercase or uppercase
Trim -- delete blank spaces at the beginning and end
String. Replace -- replace the specified character in the string with the specified character.

C # string creation process:
For example, define the variable strt = "Welcome ";
Strt + = "www.csdn.net ";
The program first creates a system. string type object and initializes it as "Welcome ". At this time, the compilation level will allocate enough memory to save the text string. Use the strt variable to represent this instance. When strt + = "www.csdn.net" is executed, the system creates a new instance and allocates enough memory to save the composite text. Then, the variable strt is used to represent the new character.
String. When you want to perform large-scale character replacement and adjustment operations, using strings will seriously affect the performance. In this case, the system. Text. stringbuilder class can be used.

The stringbuilder class does not have the powerful functions of the string class. It only provides basic replacement and Addition and deletion of text in strings, but it is very efficient, when defining a stringbuilder object, you can specify the memory capacity. If no value is specified, the system determines the size based on the string length during object initialization. The parameter length and capacity indicate the actual length of the string and the memory occupied by the string respectively. Modifying strings is performed in this memory, which greatly improves the efficiency of adding and replacing strings.
For example, define stringbuilder sb = new stringbuilder ("Hello, welcome", 100); // initialize the object and set the initial capacity to 100
SB. append ("to www.csdn.net ");
SB. Replace (old, new); // replace old with new, which is the same as string. Replace () but does not need to be copied during the process.
Stringbuilder members:
Stringbuilder sb = new stringbuilder ("www.csdn.net"); // defines the object whose initial value is www.csdn.net.
Stringbuilder sb = new stringbuilder (20); Initialize an empty object with a capacity of 20.
In addition, stringbuilder also has the maxcapacity attribute to limit the maximum capacity that an object can use. The default value is approximately Int. maxvalue (2 billion)
SB. maxcapacity = value can be defined during use;
SB. append () to append a string to the current string.
SB. appendformat () -- add a string of a specific format
SB. insert () -- insert a substring
SB. Remove () -- delete characters from the current string
SB. Replace () -- replace the character specified in the string
SB. tostring () -- converts sb to a string object

C and C currency formats.
In decimal format.
E, E scientific count (INDEX) format.
F and F are fixed points.
G.
N, N numeric format.
The r and r round-trip formats Ensure that the number converted to a string has the same value as the original number when being converted back to a number.
X and X hexadecimal formats.
Double val = math. Pi;
Console. writeline (Val. tostring (); // displays 3.14159265358979
Console. writeline (Val. tostring ("e"); // displays 3.141593e + 000
Console. writeline (Val. tostring ("F3"); // displays 3.142
Int val = 65535;
Console. writeline (Val. tostring ("X"); // displays FFFF
Console. writeline (Val. tostring ("X"); // displays FFFF
Single Val = 0.123f;
Console. writeline (Val. tostring ("p"); // displays 12.30%
Console. writeline (Val. tostring ("p1"); // displays 12.3%
By default, a space is placed between the digit and the percent sign. The customization method is as follows:
The numberformatinfo class is a member of the system. Globalization namespace. Therefore, the namespace must be imported to the program.
Single Val = 0.123f;
Object myobj = numberformatinfo. currentinfo. Clone () as numberformatinfo;
Numberformatinfo myformat = myobj as numberformatinfo;
Myformat. percentpositivepattern = 1;
Console. writeline (Val. tostring ("P", myformat); // displays 12.30%;
Console. writeline (Val. tostring ("p1", myformat); // displays 12.3%;
Formatting is flexible. The following example demonstrates a meaningless currency structure:
Double val = 1234567.89;
Int [] groupsize = {2, 1, 3 };
Object myobj = numberformatinfo. currentinfo. Clone ();
Numberformatinfo mycurrency = myobj as numberformatinfo;
Mycurrency. currencysymbol = "#"; // symbol
Mycurrency. currencydecimalseparator = ":"; // decimal point
Mycurrency. currencygroupseparator = "_"; // delimiter
Mycurrency. currencygroupsizes = groupsize;
// Output #1_234_5_67: 89
Console. writeline (Val. tostring ("C", mycurrency ));

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.