C# Strings
来源:互联网 发布:nginx url 跳转 编辑:程序博客网 时间:2024/05/16 06:22
C#的string的結尾沒有終止符,因此C# string可以嵌入任意數量的null characters (‘\0’)
string vs. System.String:C#中string是String的別名,因此它們實際上是一樣的。
// Declare without initializing.string message1;// Initialize to null.string message2 = null;// Initialize as an empty string.// Use the Empty constant instead of the literal "".string message3 = System.String.Empty;//Initialize with a regular string literal.string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";// Initialize with a verbatim string literal.string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";// Use System.String if you prefer.System.String greeting = "Hello World!";// In local variables (i.e. within a method body)// you can use implicit typing.var temp = "I'm still a strongly-typed System.String!";// Use a const string to prevent 'message4' from// being used to store another string value.const string message4 = "You can't get rid of me!";// Use the String constructor only when creating// a string from a char*, char[], or sbyte*. See// System.String documentation for details.char[] letters = { 'A', 'B', 'C' };string alphabet = new string(letters);
除了使用字符數組初始化字符串之外,不需要使用new操作符來創建字符串對象。
Immutability of String Objects
string對象是不可變的,所有對string對象的操作改變都是會返回一個新的string對象。
string s1 = "A string is more ";string s2 = "than the sum of its chars.";// Concatenate s1 and s2. This actually creates a new// string object and stores it in s1, releasing the// reference to the original object.s1 += s2;System.Console.WriteLine(s1);// Output: A string is more than the sum of its chars.
string s1 = "Hello ";string s2 = s1;s1 += "World";System.Console.WriteLine(s2);//Output: Hello
How to: Modify String Contents
using System;using System.Text;using System.Text.RegularExpressions;namespace ReplaceSubstrings{ class ReplaceSubstrings { string searchFor; string replaceWith; // Custom match method called by Regex.Replace // using System.Text.RegularExpressions string ReplaceMatchCase(Match m) { // Test whether the match is capitalized if (Char.IsUpper(m.Value[0]) == true) { // Capitalize the replacement string // using System.Text; StringBuilder sb = new StringBuilder(replaceWith); sb[0] = (Char.ToUpper(sb[0])); return sb.ToString(); } else { return replaceWith; } } static void Main(string[] args) { ReplaceSubstrings app = new ReplaceSubstrings(); string s = "The mountains are behind the clouds today."; Console.WriteLine(s); // Replace one substring with another with String.Replace. // Only exact matches are supported. s = s.Replace("mountains", "peaks"); Console.WriteLine(s); // Output: The peaks are behind the clouds today. // Use Regex.Replace for more flexibility. // Replace "the" or "The" with "many" or "Many". // using System.Text.RegularExpressions app.searchFor = "the"; // A very simple regular expression. app.replaceWith = "many"; s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase); Console.WriteLine(s); // Output: Many peaks are behind many clouds today. // Replace all occurrences of one char with another. s = s.Replace(' ', '_'); Console.WriteLine(s); // Output: Many_peaks_are_behind_many_clouds_today. // Remove a substring from the middle of the string. string temp = "many_"; int i = s.IndexOf(temp); if (i >= 0) { s = s.Remove(i, temp.Length); } Console.WriteLine(s); // Output: Many_peaks_are_behind_clouds_today. // Remove trailing and leading whitespace. // See also the TrimStart and TrimEnd methods. string s2 = " I'm wider than I need to be. "; // Store the results in a new string variable. temp = s2.Trim(); Console.WriteLine(temp); // Output: I'm wider than I need to be. // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }}
ToCharArray Method
class ModifyStrings{ static void Main() { string str = "The quick brown fox jumped over the fence"; System.Console.WriteLine(str); char[] chars = str.ToCharArray(); int animalIndex = str.IndexOf("fox"); if (animalIndex != -1) { chars[animalIndex++] = 'c'; chars[animalIndex++] = 'a'; chars[animalIndex] = 't'; } string str2 = new string(chars); System.Console.WriteLine(str2); // Keep the console window open in debug mode System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); }}/* Output: The quick brown fox jumped over the fence The quick brown cat jumped over the fence */
fixed keyword unsafe operations
using System;namespace UnsafeString{ class Program { unsafe static void Main(string[] args) { // Compiler will store (intern) // these strings in same location. string s1 = "Hello"; string s2 = "Hello"; Console.WriteLine(s1); // Hello Console.WriteLine(s2); // Hello // Change one string using unsafe code. fixed (char* p = s1) { p[0] = 'C'; } // Both strings have changed. Console.WriteLine(s1); // Cello Console.WriteLine(s2); // Cello // Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }}
Regular and Verbatim String Literals
string columns = "Column 1\tColumn 2\tColumn 3";//Output: Column 1 Column 2 Column 3string rows = "Row 1\r\nRow 2\r\nRow 3";/* Output: Row 1 Row 2 Row 3*/string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";//Output: "The Æolean Harp", by Samuel Taylor Coleridge
string filePath = @"C:\Users\scoleridge\Documents\";//Output: C:\Users\scoleridge\Documents\string text = @"My pensive SARA ! thy soft cheek reclined Thus on mine arm, most soothing sweet it is To sit beside our Cot,...";/* Output:My pensive SARA ! thy soft cheek reclined Thus on mine arm, most soothing sweet it is To sit beside our Cot,... */string quote = @"Her name was ""Sara.""";//Output: Her name was "Sara."
String Escape Sequences
Escape sequence
Character name
Unicode encoding
\’
Single quote
0x0027
\”
Double quote
0x0022
\\
Backslash
0x005C
\0
Null
0x0000
\a
Alert
0x0007
\b
Backspace
0x0008
\f
Form feed
0x000C
\n
New line
0x000A
\r
Carriage return
0x000D
\t
Horizontal tab
0x0009
\U
Unicode escape sequence for surrogate pairs.
\Unnnnnnnn
\u
Unicode escape sequence
\u0041 = “A”
\v
Vertical tab
0x000B
\x
Unicode escape sequence similar to “\u” except with variable length.
\x0041 = “A”
For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\\files.txt".
Format Strings
class FormatString{ static void Main() { // Get user input. System.Console.WriteLine("Enter a number"); string input = System.Console.ReadLine(); // Convert the input string to an int. int j; System.Int32.TryParse(input, out j); // Write a different string each iteration. string s; for (int i = 0; i < 10; i++) { // A simple format string with no alignment formatting. s = System.String.Format("{0} times {1} = {2}", i, j, (i * j)); System.Console.WriteLine(s); } //Keep the console window open in debug mode. System.Console.ReadKey(); }}
Formatting Types in the .NET Framework
Substrings
string s3 = "Visual C# Express";System.Console.WriteLine(s3.Substring(7, 2));// Output: "C#"System.Console.WriteLine(s3.Replace("C#", "Basic"));// Output: "Visual Basic Express"// Index values are zero-basedint index = s3.IndexOf("C");// index = 7
How to: Search Strings Using String Methods
class StringSearch{ static void Main() { string str = "Extension methods have all the capabilities of regular static methods."; // Write the string and include the quotation marks. System.Console.WriteLine("\"{0}\"", str); // Simple comparisons are always case sensitive! bool test1 = str.StartsWith("extension"); System.Console.WriteLine("Starts with \"extension\"? {0}", test1); // For user input and strings that will be displayed to the end user, // use the StringComparison parameter on methods that have it to specify how to match strings. bool test2 = str.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase); System.Console.WriteLine("Starts with \"extension\"? {0} (ignoring case)", test2); bool test3 = str.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase); System.Console.WriteLine("Ends with '.'? {0}", test3); // This search returns the substring between two strings, so // the first index is moved to the character just after the first string. int first = str.IndexOf("methods") + "methods".Length; int last = str.LastIndexOf("methods"); string str2 = str.Substring(first, last - first); System.Console.WriteLine("Substring between \"methods\" and \"methods\": '{0}'", str2); // Keep the console window open in debug mode System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); }}/*Output:"Extension methods have all the capabilities of regular static methods."Starts with "extension"? FalseStarts with "extension"? True (ignoring case)Ends with '.'? TrueSubstring between "methods" and "methods": ' have all the capabilities of regular static 'Press any key to exit. */
Accessing Individual Characters
string s5 = "Printing backwards";for (int i = 0; i < s5.Length; i++){ System.Console.Write(s5[s5.Length - i - 1]);}// Output: "sdrawkcab gnitnirP"
string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";System.Text.StringBuilder sb = new System.Text.StringBuilder(question);for (int j = 0; j < sb.Length; j++){ if (System.Char.IsLower(sb[j]) == true) sb[j] = System.Char.ToUpper(sb[j]); else if (System.Char.IsUpper(sb[j]) == true) sb[j] = System.Char.ToLower(sb[j]);}// Store the new string.string corrected = sb.ToString();System.Console.WriteLine(corrected);// Output: How does Microsoft Word deal with the Caps Lock key?
Null Strings and Empty Strings
string s = String.Empty;
static void Main(){ string str = "hello"; string nullStr = null; string emptyStr = String.Empty; string tempStr = str + nullStr; // Output of the following line: hello Console.WriteLine(tempStr); bool b = (emptyStr == nullStr); // Output of the following line: False Console.WriteLine(b); // The following line creates a new empty string. string newStr = emptyStr + nullStr; // Null strings and empty strings behave differently. The following // two lines display 0. Console.WriteLine(emptyStr.Length); Console.WriteLine(newStr.Length); // The following line raises a NullReferenceException. //Console.WriteLine(nullStr.Length); // The null character can be displayed and counted, like other chars. string s1 = "\x0" + "abc"; string s2 = "abc" + "\x0"; // Output of the following line: * abc* Console.WriteLine("*" + s1 + "*"); // Output of the following line: *abc * Console.WriteLine("*" + s2 + "*"); // Output of the following line: 4 Console.WriteLine(s2.Length);}
Using StringBuilder for Fast String Creation
System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");sb[0] = 'C';System.Console.WriteLine(sb.ToString());System.Console.ReadLine();//Outputs Cat: the ideal pet
class TestStringBuilder{ static void Main() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Create a string composed of numbers 0 - 9 for (int i = 0; i < 10; i++) { sb.Append(i.ToString()); } System.Console.WriteLine(sb); // displays 0123456789 // Copy one character of the string (not possible with a System.String) sb[0] = sb[9]; System.Console.WriteLine(sb); // displays 9123456789 }}
相關課目:
Topic
Description
How to: Modify String Contents (C# Programming Guide)
Provides a code example that illustrates how to modify the contents of strings.
How to: Concatenate Multiple Strings (C# Programming Guide)
Illustrates how to use the + operator and the Stringbuilder class to join strings together at compile time and run time.
How to: Compare Strings (C# Programming Guide)
Shows how to perform ordinal comparisons of strings.
How to: Parse Strings Using String.Split (C# Programming Guide)
Contains a code example that illustrates how to use the String.Split method to parse strings.
How to: Search Strings Using String Methods (C# Programming Guide)
Explains how to use specific methods to search strings.
How to: Search Strings Using Regular Expressions (C# Programming Guide)
Explains how to use regular expressions to search strings.
How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)
Shows how to safely parse a string to see whether it has a valid numeric value.
How to: Convert a String to a DateTime (C# Programming Guide)
Shows how to convert a string such as “01/24/2008” to a System.DateTime object.
Basic String Operations in the .NET Framework
Provides links to topics that use System.String and System.Text.StringBuilder methods to perform basic string operations.
Parsing Strings in the .NET Framework
Describes how to insert characters or empty spaces into a string.
Comparing Strings in the .NET Framework
Includes information about how to compare strings and provides examples in C# and Visual Basic.
Using the StringBuilder Class in the .NET Framework
Describes how to create and modify dynamic string objects by using the StringBuilder class.
LINQ and Strings
Provides information about how to perform various string operations by using LINQ queries.
C# Programming Guide
Provides links to topics that explain programming constructs in C#.
- C# Strings
- Leetcode-43-Multiply Strings C#
- 【LeetCode】C# 43、Multiply Strings
- c#生成唯一ID(strings&numbers )
- C#使用Strings.StrConv进行简繁体转换
- C#使用Strings.StrConv进行简繁体转换
- 浅析如何去除Strings中的C#空格
- Strings
- Strings
- strings
- Strings
- Strings
- Strings
- strings
- Strings
- How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings
- Foundation - strings
- Localizable.strings
- Java面试题大全(Java基础十二)
- NOIP提高组【JZOJ4804】成绩调研
- ionic 底部tab模块切换,使用背景图片
- JavaMail--基础类详解
- 常用的一些算法稳定性分析
- C# Strings
- ios developer tiny share-20160920
- OkHttp的使用
- 悬浮窗错误android.view.WindowManager$BadTokenException: permission denied for this window type
- js中的call函数
- 多个时间段统计
- json解析数组
- specified for property 'resourceFile' does not exist
- 在Neatbeans中使用JUnit4的学习时的总结