String operations can be seen everywhere in daily programming in any programming language. Today, let’s summarize some knowledge points about strings in C# that you may forget or miss.
Word-by-word string
In a normal string, the backslash character is an escape character. In Verbatim Strings, characters will be interpreted by the programmer in its original meaning. Using a verbatim string simply prefix the string with the @ symbol.
// Word-by-word string: escape charactervar filename = @"c:\temp\"; (filenaame); // Word-by-character string: multi-line textvar multiLine = @"This is a multiline paragraph."; (multiLine); // Non-word stringvar escapedFilename = "c:\temp\"; (escapedFilename);
Output:
c:\temp\
This is a
multiline paragraph.
c: emp
The only character in a verbatim string that is not interpreted as is is are double quotes. Since double quotes are the key characters that define strings, double quotes need to be escaped in verbatim strings.
varstr = @"""I don't think so"", he said."; (str); // Output:"I don't think so", he said.
String interpolation can also be implemented in word-by-word strings.
($@"Testing \n 1 2 {5 - 2}"); // Output: Testing \n 1 2 3
Digital format conversion
A typical formatting method is:
("{index[:format]}", number)
The "0" and "#" placeholders can be used for complementation. "0" means that if the number of digits is not enough, the number of digits will be supplemented. If the number of digits is too high, it will be rounded; "#" means placeholding, which is used to assist "0" in filling.
Standard formatting usage:
// "0" description: placeholder, fill bit if possible("{0:000000}",1234); // Result: 001234 // “#"Description: Placeholder, if possible, fill the bit("{0:######}",1234); // Result: 1234("{0:#0####}",1234); // Result: 01234("{0:0#0####}",1234); // Result: 0001234 // "." Description: decimal point("{0:000.000}", 1234); // Result: 1234.000("{0:000.000}", 4321.12543); // Result: 4321.125 // "," Description: Thousands of points("{0:0,0}", 1234567); //Result: 1,234,567 // "%" description: Formatted as percentage("{0:0%}",1234); // Results: 123400%("{0:#%}", 1234.125); // Result: 123413%("{0:0.00%}",1234); // Result: 123400.00%("{0:#.00%}",1234.125); // result:123412.50%
Built-in shortcut letter formatting usage:
// E-scientific notation method(25000).ToString("E"); // Result: 2.500000E+004 // C-currency representation, with comma separator, two digits are retained after the decimal point by default, rounded(2.5).ToString("C"); // Result: ¥2.50 // D[length]-decimal number(25).ToString("D5"); // Result: 00025 // F[precision] - Floating point number, retaining decimal places (rounded)(25).ToString("F2"); // Result: 25.00 // G[digits] - regular, keep the specified number of significant digits, rounded(2.52).ToString("G2"); // Results: 2.5 // N-with comma separator, two digits are retained after the decimal point by default, rounded(2500000).ToString("N"); // Result: 2,500,000.00 // X-hexadecimal, non-integer will generate format exceptions(255).ToString("X"); // result:FF
ToString
You can also customize the zero-complement format:
(15).ToString("000"); // Result: 015(15).ToString("value is 0"); // Result: value is 15(10.456).ToString("0.00"); // Result: 10.46(10.456).ToString("00"); // Results: 10(10.456).ToString("value is 0.0"); // result:value is 10.5
Convert to binary, octal, hexadecimal output:
int number = 15; (number, 2); // Result: 1111(number, 8); // Results: 17(number, 16); // result:f
Custom Formatizer:
public class CustomFormat : IFormatProvider, ICustomFormatter { public string Format(string format, object arg, IFormatProvider formatProvider) { if (!(formatProvider)) { return null; } if (format == "Reverse") { return ("", ().Reverse()); } return (); } public object GetFormat(Type formatType) { return formatType == typeof(ICustomFormatter) ? this : null; } }
Using a custom formatter:
(newCustomFormat(), "-> {0:Reverse} <-", "Hello World"); // Output:-> dlroW olleH <-
String stitching
Stitch the strings in the array into one string:
var parts = new[] { "Foo", "Bar", "Fizz", "Buzz"}; var joined = (", ", parts); // joined = "Foo, Bar, Fizz, Buzz"
The following four methods can achieve the purpose of the same string splicing:
string first = "Hello"; string second = "World"; string foo = first + " " + second; string foo = (first, " ", second); string foo = ("{0} {1}", firstname, lastname); string foo = $"{firstname} {lastname}";
String interpolation
Simple usage:
var name = "World"; var str =$"Hello, {name}!"; // str = "Hello, World!"
Format with date:
var date = ; var str = $"Today is {date:yyyy-MM-dd}!";
Padding:
var number = 42; // Make up to the leftvar str = $"The answer to life, the universe and everything is {number, 5}."; // str = "The answer to life, the universe and everything is ___42." ('_' means space) // Make up to the rightvar str = $"The answer to life, the universe and everything is ${number, -5}."; // str = "The answer to life, the universe and everything is 42___."
Combined with built-in shortcut letter formatting:
var amount = 2.5; var str = $"It costs {amount:C}"; // str = "¥2.50" var number = 42; var str = $"The answer to life, the universe and everything is {number, 5:f1}."; // str = "The answer to life, the universe and everything is ___42.1"
The above is the detailed content of the summary of C# string operations. For more information about C# string operations, please pay attention to my other related articles!