.NET教程 - 字符串 & 编码 & 正则表达式(String & Encoding & Regular Express)
更新记录
转载请注明出处:
2022年9月28日 发布。
2022年9月28日 从笔记迁移到博客。
System.char
说明
single Unicode character
aliases the System.Char struct
char c = 'A';
char newLine = '\n';
常见转义字符
常用静态方法
判断是否字母
使用Char.IsLetter静态方法
Console.WriteLine(Char.IsLetter('a'));//true
判断是否数字
使用Char.IsDigit静态方法
Console.WriteLine(Char.IsDigit('9'));//true
判断是否字母数字
使用Char.IsLetterOrDigit静态方法
Console.WriteLine(Char.IsLetterOrDigit('9'));//true
判断是否空格
使用Char.IsSeparator静态方法
Console.WriteLine(Char.IsWhiteSpace(' '));//true
判断是否标点符号
使用Char.IsPunctuation静态方法
Console.WriteLine(Char.IsPunctuation(','));//true
### 判断是否可打印字符
使用Char.IsSymbol静态方法
```c#
Console.WriteLine(Char.IsSymbol('\r'));//false
判断是否控制字符
使用Char.IsContorl静态方法
Console.WriteLine(Char.IsControl('\n'));//true
判断是否分隔符
使用Char.IsSeparato静态方法
Console.WriteLine(Char.IsSeparator(' '));//true
判断是否大写
使用Char.IsUpper静态方法
Console.WriteLine(Char.IsUpper('A'));//true
判断是否小写
使用Char.IsLower静态方法
Console.WriteLine(Char.IsLower('a'));//true
转为大写
使用Char.ToUpper静态方法
Console.WriteLine(Char.ToUpper('a'));
转为小写
使用Char.ToLower静态方法
Console.WriteLine(Char.ToLower('A'));
System.String
String对象介绍
String 对象是表示字符串 System.Char 对象的有序集合, BCL中System.String类
System.Char 对象对应于 UTF-16 代码单元(Unicode字符串数组)
内存中 String 对象的最大大小为2GB,或大约1000000000个字符
官方文档:
https://docs.microsoft.com/zh-cn/dotnet/api/system.string?view=netframework-4.8
不可变性(Imutable)
通常字符串方法处理后返回一个新的字符串,而不是修改原有字符串
String是不可变的(即它是只读的),需要可变可以使用System.Text.StringBuilder
字符串是不变的(immutable),不可以修改,目的是提高效率
逐字前缀
使用@放在字符串前面即可,这样可以防止内容被转义
string str = @"\a \b \d \t\x";
实例化字符串对象
通过将字符串文本赋给 String 变量
string str1 = "Panda 666";
string str2 = @"https://www.panda666.com";
通过构造函数(Constructing Strings)
//指定字符重复
string str3 = new string('A',10);
//字符数组转为字符串
char[] charArray = { 'a','b','c','d'};
string str4 = new string(charArray);
//字符数组转为字符串,指定开始和长度
string str5 = new string(charArray,1,charArray.Length-1);
//逐字字符串
string s3 = @"\\server\fileshare\panda.cs";
初始化建议
如果不定义初始值,使用String.Empty进行赋值
string str = String.Empty;
Null Strings and Empty Strings
Null strings
A string that has been declared but has not been assigned a value is null
Attempting to call methods on that string throws a NullReferenceException
实例:
string nullString = null;
Console.WriteLine (nullString == null); // True
Console.WriteLine (nullString == ""); // False
Console.WriteLine (nullString.Length == 0); //NullReferenceException
Empty strings
string whose value is "" or String.Empty
实例:
string empty = "";
Console.WriteLine (empty == ""); // True
Console.WriteLine (empty == string.Empty); // True
Console.WriteLine (empty.Length == 0); // True
检测Null或String.Empty的办法
使用String.IsNullOrEmpty()静态方法,等同于:if (str == null || str.Equals(String.Empty))
实例:
string str = String.Empty;
if(String.IsNullOrEmpty(str))
{
str = "Panda 666";
}
检测Null或String.Empty或空白字符串的方法
使用String. IsNullOrWhiteSpace()静态方法,等同于:
if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty))
实例:
string str = "";
if(String.IsNullOrWhiteSpace(str))
{
str = "Panda666";
}
访问字符串成员通过索引(Accessing characters within a string)
string str = "Panda666";
Console.WriteLine(str[0]);
Console.WriteLine(str[1]);
Console.WriteLine(str[str.Length-1]);
Console.WriteLine(str);
遍历字符串
string类型实现了IEnumerable
实例:
foreach (char c in "123")
{
Console.Write(c + ","); // 1,2,3,
}
格式化(Format)
使用String.Format函数
string result = String.Format("Panda{0}.com", 666);
使用$作为字符串的前缀即可实现
int code = 666;
string website = "Panda666.com";
string result = $"Website = {website}, code = {code}";
注意:如果需要在字符串中使用{},输入{{}}即可
插值字符串也支持格式化:
string.Format($"Product Name:{name}, Price:{price:C2}, Related {relatedName}")
插值字符串(Interpolated strings)
简单使用:
string.Format($"Product Name:{name}, Price:{price:C2}, Related {relatedName}")
跨越多行:
插值字符串跨越多行需要使用@前缀
实例:
int x = 666;
string s = $@"this spans {
x} lines";
字符与字符串比较(Compare)注意
There are two basic algorithms for string comparison:
Ordinal:interpret characters as numbers (according to their numeric Unicode value)
Culture sensitive:interpret characters with reference to a particular alphabet
two special cultures:
current culture:based on settings picked up from the computer’s control panel
invariant culture:same on every computer (and closely matches American culture)
普通的字符串比较可以使用:==运算符 或者 equal方法
如果需要使用指定的文化进行比较,可以使用String类型的静态方法Compare
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
CultureInfo german = CultureInfo.GetCultureInfo("de-DE");
int i = string.Compare("Müller", "Muller", false, german);
//wait
Console.ReadKey();
}
}
}
字符串连接运算符
+号在字符串运算中作为连接运算符
string str = "Panda" + "666";
字符串操作
说明
所有字符串修改方法都将返回新的 String 对象
它们不会修改当前实例的值
空字符串
说明:空字符串,此字段为只读
注意:这是一个静态成员
string str = String.Empty;
字符串的长度
语法:
str.Length
实例:
string str1 = String.Empty;
Console.WriteLine(str1.Length); //0
string str2 = "Panda666";
Console.WriteLine(str2.Length); //8
字符串转为大写
语法:
public string ToUpper ();
实例:
string str = " Panda666.com ";
string str2 = str.ToUpper();
Console.WriteLine(str2);
字符串转为小写
语法:
public string ToLower ();
实例:
string str = " Panda666.com ";
string str2 = str.ToLower();
Console.WriteLine(str2);
转为字符数组
语法:
public char[] ToCharArray (int startIndex, int length);
public char[] ToCharArray ();
实例:
string str = "Panda666.com";
char[] charArray = str.ToCharArray();
foreach (char item in charArray)
{
Console.WriteLine(item);
}
检测开头
语法:
public bool StartsWith (string value);
实例:
string str = "Panda666.com";
bool result = str.StartsWith("Panda");
Console.WriteLine(result);//true
检测结尾
语法:
public bool EndsWith (string value);
实例:
string str = "Panda666.com";
bool result = str.EndsWith("com");
Console.WriteLine(result);//true
检测包含
语法:
public bool Contains (string value);
实例:
string panda = "panda666.com";
Console.WriteLine(panda.Contains("panda"));
检查包含字符
使用IndexOfAny可以快速找到要查找的多个字符中的一个
string pandaTest = "https://www.panda666.com";
int index = pandaTest.IndexOfAny(new char[] {'a','c','d','1' });
int index2 = pandaTest.IndexOfAny(new char[] {'a','c','d','1' },2);
Console.WriteLine(index);
Console.WriteLine(index2);
开头填充
语法:
public string PadLeft (int totalWidth, char paddingChar);
public string PadLeft (int totalWidth);
实例:
结尾填充
语法:
public string PadRight (int totalWidth, char paddingChar);
public string PadRight (int totalWidth);
实例:
字符串反转
using System;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string a = "panda";
Console.WriteLine(StringReverse(a));
//wait
Console.ReadKey();
}
private static string StringReverse(string input)
{
var stringCharArr = input.ToCharArray();
Array.Reverse(stringCharArr);
return new String(stringCharArr);
}
}
}
插入字符串
语法:
public string Insert (int startIndex, string value);
实例:
搜索字符串
语法:
public int IndexOf (char value);
public int IndexOf (char value, int startIndex);
public int IndexOf (char value, int startIndex, int count);
public int IndexOf (string value);
public int IndexOf (string value, int startIndex);
public int IndexOf (string value, int startIndex, int count);
实例:
搜索字符串(最后)
语法:
public int LastIndexOf (char value);
public int LastIndexOf (char value, int startIndex);
public int LastIndexOf (char value, int startIndex, int count);
public int LastIndexOf (string value);
public int LastIndexOf (string value, int startIndex);
public int LastIndexOf (string value, int startIndex, int count);
实例:
字符串提取子字符串
语法:
public string Substring (int startIndex);
public string Substring (int startIndex, int length);
实例:
string str = "Panda666.com";
string str2 = str.Substring(0,str.Length-3);
Console.WriteLine(str2);
字符串比较相等
语法:
public override bool Equals (object obj);
public bool Equals (string value);
public bool Equals (string value, StringComparison comparisonType);
public static bool Equals (string a, string b);
public static bool Equals (string a, string b, StringComparison comparisonType);
注意:包含实例方法和静态方法
实例:
插入字符串
语法:
public string Insert (int startIndex, string value);
实例:
替换字符串
语法:
public string Replace (char oldChar, char newChar);
public string Replace (string oldValue, string newValue);
实例:
删除字符串开头和结尾字符
语法:
public string Trim (params char[] trimChars);
说明:
如果 trimChars 为 null 或空数组,则改为移除空白字符
实例:
string str = " Panda666.com ";
string str2 = str.Trim();
Console.WriteLine(str2);
删除字符串末尾字符
语法:
public string TrimEnd (params char[] trimChars);
注意:如果参数为null 或空数组,则改为删除 Unicode 空白字符
实例:
string str = "Panda666.com";
string str2 = str.TrimEnd(new char[]{ 'c', 'o', 'm' });
Console.WriteLine(str2); //Pada666.
删除字符串开头字符
语法:
public string TrimStart (params char[] trimChars);
注意:如果参数为null 或空数组,则改为删除 Unicode 空白字符
实例:
string str = "Panda666.com";
string str2 = str.TrimStart(new char[] { 'P', 'a', 'n' });
Console.WriteLine(str2); //da666.com
删除指定位置字符
语法:
public string Remove (int startIndex);
public string Remove (int startIndex, int count);
实例:
分隔字符串
语法:
public string[] Split (params char[] separator);
public string[] Split (char[] separator, int count);
public string[] Split (char[] separator, StringSplitOptions options);
public string[] Split (char[] separator, int count, StringSplitOptions options);
public string[] Split (string[] separator, StringSplitOptions options);
public string[] Split (string[] separator, int count, StringSplitOptions options);
实例:
拼接字符串
语法:
public static string Join (string separator, string[] value);
public static string Join (string separator, params object[] values);
public static string Join (string separator, string[] value, int startIndex, int count);
public static string Join (string separator, System.Collections.Generic.IEnumerable<string> values);
public static string Join<T> (string separator, System.Collections.Generic.IEnumerable<T> values);
实例:
连接字符串
语法:
public static string Concat (string str0, string str1);
public static string Concat (string str0, string str1, string str2);
public static string Concat (string str0, string str1, string str2, string str3);
public static string Concat (params string[] values);
public static string Concat (object arg0);
public static string Concat (object arg0, object arg1);
public static string Concat (object arg0, object arg1, object arg2);
public static string Concat (object arg0, object arg1, object arg2, object arg3);
public static string Concat (params object[] args);
public static string Concat (System.Collections.Generic.IEnumerable<string> values);
public static string Concat<T> (System.Collections.Generic.IEnumerable<T> values);
注意:这是一个静态方法
实例:
字符串比较
实例:不区分大小写的字符串比较
string str1 = "PANDA666";
string str2 = "panda666";
//不分区大小写的比较
int result = String.Compare(str1, str2, true);
Console.WriteLine(result); //0
检测NULL和空字符串
语法:
public static bool IsNullOrEmpty (string value);
注意:这是一个静态方法
实例:
检测NULL和空字符串和空白字符串
语法:
public static bool IsNullOrWhiteSpace (string value);
注意:这是一个静态方法
实例:
字符串格式化
string result = String.Format("http://{0}", "www.panda666.com");
实例:
string composite = "It's {0} degrees in {1} on this {2} morning";
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);
// s == "It's 35 degrees in Perth on this Friday morning"
还可以使用格式修饰符
string composite = "Name={0,-20} Credit Limit={1,15:C}";
Console.WriteLine (string.Format (composite, "Mary", 500));
Console.WriteLine (string.Format (composite, "Elizabeth", 20000));
格式化小数位
$"The area of the circle is: { area : 0.00 }");
从C# 6开始支持插值字符串
string v1 = "Panda666.com";
string v2 = "666";
string panda = $"v1:{v1} v2:{v2}";
实例:
string s = $"It's hot this {DateTime.Now.DayOfWeek} morning";
自定义类型格式化
使用IFormatable接口实现自定义类型格式化
using System;
namespace Test
{
class Animal:IFormattable
{
public int Code { get; set; }
public string Name { get; set; }
public Animal(int code, string name)
{
this.Code = code;
this.Name = name;
}
/// <summary>
/// 自定义字符串格式化
/// </summary>
/// <param name="format">自定义格式</param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider = null)
{
switch(format)
{
case "Code":
return this.Code.ToString();
case "Name":
return this.Name.ToString();
default:
return this.ToString();
}
}
}
class TestClass
{
public static void Main()
{
Animal animal = new Animal(666, "Panda");
//自定义字符串格式化
Console.WriteLine(animal.ToString("Code"));
Console.WriteLine(animal.ToString("Name"));
Console.ReadKey();
}
}
}
System.Text.StringBulider
说明
StringBulider类是BCL的成员,位于System.Text命名空间下
StringBulider对象是Unicode字符的可变mutable (editable)数组
StringBulider maximum capacity default is int.MaxValue
命名空间
System.Text
释放内存
如果为stringBuilder分配了比较大的内存需要回收,最好为其赋值新的实例。
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
// 假如分配了大块内存
for (int i = 0; i < 10000; i++)
{
stringBuilder.Append("Panda|");
}
//重设实例
stringBuilder = new System.Text.StringBuilder();
实例
新建一个StringBuilder
StringBuilder stringBuilder = new StringBuilder();
追加一个字符串到StringBuilder
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Panda666.com");
插入一个字符串到StringBuilder
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Panda666.com");
stringBuilder.Insert(0, "www.");
移除一个字符串
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Panda666.com");
stringBuilder.Insert(0, "www.");
stringBuilder.Remove(0,4);
替换字符串
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Panda666.com");
stringBuilder.Insert(0, "www.");
stringBuilder.Replace("www", "cdn");
转为String类型
stringBuilder.ToString();
清除内容
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
stringBuilder.Append("Panda666.com");
stringBuilder.Clear();
System.Text.Encoding
说明
Encoding类型用于表示编码的类型
其他具体的编码类型都是Encoding类型的子类
常用于File和Stream处理中的编码
注意:UTF-8 is the default text encoding for all file and stream I/O
所在命名空间:
using System.Text;
常见编码类型
UTF-8 Encoding.UTF8
UTF-16 Encoding.Unicode (not UTF16)
UTF-32 Encoding.UTF32
ASCII Encoding.ASCII
建立一个编码对象
使用预定义编码类型的静态属性
Encoding ascii = Encoding.ASCII;
Encoding utf8 = Encoding.UTF8;
Encoding utf32 = Encoding.UTF32;
Encoding utf7 = Encoding.UTF7;
Encoding unicode = Encoding.Unicode; //注意:这不是UTF-16
使用GetEncoding方法
Encoding utf8 = Encoding.GetEncoding("utf-8");
Encoding ascii = Encoding.GetEncoding("us-ascii");
使用GetEncodings静态方法获得所有编码类型
using System;
using System.Text;
foreach (var item in Encoding.GetEncodings())
{
Console.WriteLine(item.Name);
//utf-16
//utf - 16BE
//utf - 32
//utf - 32BE
//us - ascii
//iso - 8859 - 1
//utf - 7
//utf - 8
}
编码转换
字节数值与字符串相互转换
// String to Byte Arrays
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes("0123456789");
byte[] utf16Bytes = System.Text.Encoding.Unicode.GetBytes("0123456789");
byte[] utf32Bytes = System.Text.Encoding.UTF32.GetBytes("0123456789");
Console.WriteLine(utf8Bytes.Length); // 10
Console.WriteLine(utf16Bytes.Length); // 20
Console.WriteLine(utf32Bytes.Length); // 40
// Byte Arrays to String
string original1 = System.Text.Encoding.UTF8.GetString(utf8Bytes);
string original2 = System.Text.Encoding.Unicode.GetString(utf16Bytes);
string original3 = System.Text.Encoding.UTF32.GetString(utf32Bytes);
Console.WriteLine(original1); // 0123456789
Console.WriteLine(original2); // 0123456789
Console.WriteLine(original3); // 0123456789
字节数组转为字符串
使用编码对象的GetBytes方法即可
string website = "Panda666.com";
byte[] result = Encoding.UTF8.GetBytes(website);
foreach (var item in result)
{
Console.WriteLine(item);
}
字符串转为字节数组
使用编码对象的GetString方法即可
string website = "Panda666.com";
byte[] byteUtf8 = Encoding.UTF8.GetBytes(website);
string result = Encoding.UTF8.GetString(byteUtf8);
写入文件时设置编码类型
System.IO.File.WriteAllText ("data.txt", "Testing...", Encoding.Unicode);
注意:如果省略编码类型,则会使用UTF-8类型。
System.Security.SecureString
说明
用于存储加密的文本
实例
using System;
using System.Security;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
SecureString secureString = new SecureString();
secureString.AppendChar('c');
Console.WriteLine(secureString.ToString());
//wait
Console.ReadKey();
}
}
}
正则表达式(Regular expressions)
说明
常用正则语法
命名空间
System.Text.RegularExpressions
相关类型
Regex
实例
实例:进行字符串正则匹配一次(静态方法)
string inputString = "http://www.panda666.com";
string pattern = "www";
Match match = Regex.Match(inputString, pattern);
//是否匹配成功
Console.WriteLine(match.Success); //True
//匹配到的内容
Console.WriteLine(match.Value); //www
//匹配成功的第一个位置
Console.WriteLine(match.Index); //7
实例:进行字符串正则匹配一次(实例方法)
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
//获得用户输入
Console.WriteLine("Input Word");
string input = Console.ReadLine();
//匹配数字
var ageChecker = new Regex(@"\d{1,3}");
//var ageChecker = new Regex(@"^\d$");
if (ageChecker.IsMatch(input))
{
Console.WriteLine("Get Age! Is {0}", input);
}
else
{
Console.WriteLine("I don't konw your Age");
}
//wait
Console.ReadKey();
}
}
}
实例:进行字符串正则匹配多次
string inputString = "http://www.panda666.comhttp://www.panda666.com";
string pattern = "www";
MatchCollection matches = Regex.Matches(inputString, pattern);
foreach (Match item in matches)
{
Console.WriteLine(item.Success);
Console.WriteLine(item.Value);
Console.WriteLine(item.Index);
}
实例:替换字符串
public string Replace(string input, string replacement)
代码:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Regex regex = new Regex("Panda666");
string testString = "www.Panda666.com";
string result = regex.Replace(testString, "222dog");
Console.WriteLine(result);
//wait
Console.ReadKey();
}
}
}
实例:分割字符串
public string[] Split(string input)
代码:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Regex regex = new Regex("Panda666");
string testString = "www.Panda666.com";
string[] result = regex.Split(testString);
foreach (string item in result)
{
Console.WriteLine(item);
}
//wait
Console.ReadKey();
}
}
}
Base64处理
Base64编码
//Base64编码
var username = "username";
var password = "password";
var byteEncoding = System.Text.UTF8Encoding.UTF8.GetBytes($"{ username}:{ password}");
var base64Str = System.Convert.ToBase64String(byteEncoding);
Console.WriteLine(base64Str); //dXNlcm5hbWU6cGFzc3dvcmQ=
Base64解码
//Base64解码
var byteDecoding = System.Convert.FromBase64String(base64Str);
string originStr = System.Text.UTF32Encoding.UTF8.GetString(byteDecoding);
Console.WriteLine(originStr); //username:password
格式化
格式说明符构成
格式:
{位置,对齐占位数:修饰符(精度)}
索引号(index)、对齐说明符(alignment)、格式(format)
注意:格式(format)还可以包含附加字段
常用数值类型格式说明符
格式说明符列表
实例
基本使用
Console.WriteLine("{0}", 666); //666
格式化左对齐
Console.WriteLine("{0,-10}",666);//666
格式化右对齐
Console.WriteLine("{0,10}",666); // 666
格式化金额
Console.WriteLine("{0:C}",6666.66M); //¥6,666.66
格式化百分比
Console.WriteLine("{0:P}",0.8633); //86.33%
Console.WriteLine("{0:P3}",0.8633); //86.330%
格式化千分符
Console.WriteLine("{0:N}", 45664166.3663M); //45,664,166.37
Console.WriteLine("{0:N2}", 45664166.3663M); //45,664,166.37
Console.WriteLine("{0:N3}", 45664166.3663M); //45,664,166.366
格式化十六进制
Console.WriteLine("{0:X}",123); //7B
Console.WriteLine("{0:x}",123); //7b
货币格式化
货币符号
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//中国
CultureInfo cn = CultureInfo.GetCultureInfoByIetfLanguageTag("zh-CN");
//中国澳门
CultureInfo mo = CultureInfo.GetCultureInfoByIetfLanguageTag("zh-MO");
//中国香港
CultureInfo hk = CultureInfo.GetCultureInfoByIetfLanguageTag("zh-HK");
//中国台湾
CultureInfo tw = CultureInfo.GetCultureInfoByIetfLanguageTag("zh-TW");
//美国
CultureInfo us = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
//日本
CultureInfo jp = CultureInfo.GetCultureInfoByIetfLanguageTag("ja-JP");
//输出测试
Console.WriteLine("人民币 {0}", 666666.ToString("C", cn));
Console.WriteLine("台币 {0}",666666.ToString("C", mo));
Console.WriteLine("港元 {0}",666666.ToString("C", hk));
Console.WriteLine("澳元 {0}",666666.ToString("C", tw));
Console.WriteLine("美元 {0}",666666.ToString("C", us));
Console.WriteLine("日元 {0}",666666.ToString("C", jp));
//wait
Console.ReadKey();
}
}
}
千分位分隔符
//正常数值输出
Console.WriteLine("G {0:G}",66666666.66M);
//三位一个分隔符
Console.WriteLine("N {0:N}", 666666.66M);
数值小数位
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double number = 123123.1231D;
//123123.1
Console.WriteLine(number.ToString("0.0"));
//123123.12
Console.WriteLine(number.ToString("0.00"));
//123123.123
Console.WriteLine(number.ToString("0.000"));
//123123.1231
Console.WriteLine(number.ToString("0.0000"));
//123123.12310
Console.WriteLine(number.ToString("0.00000"));
//123123.123100
Console.WriteLine(number.ToString("0.000000"));
//123123.1231000
Console.WriteLine(number.ToString("0.0000000"));
//与0.0000区别在于#仅显示有效位
//123123.1
Console.WriteLine(number.ToString("#.#"));
//123123.12
Console.WriteLine(number.ToString("#.##"));
//123123.123
Console.WriteLine(number.ToString("#.###"));
//123123.1231
Console.WriteLine(number.ToString("#.####"));
//123123.1231
Console.WriteLine(number.ToString("#.#####"));
//123123.1231
Console.WriteLine(number.ToString("#.######"));
//123123.1231
Console.WriteLine(number.ToString("#.#######"));
//wait
Console.ReadKey();
}
}
}
常用日期类型格式说明符
格式化字符
实例
实例:格式化日期
Console.WriteLine("{0:D}", DateTime.Now);//2020年4月20日
Console.WriteLine("{0:d}", DateTime.Now);//2020/4/20
实例:格式化小数位
$"The area of the circle is: { area : 0.00 }");
长日期短日期格式
长日期修饰符D,短日期修饰符d
//长日期
Console.WriteLine("{0:D}", DateTime.Now);
//短日期
Console.WriteLine("{0:d}", DateTime.Now);
自定义日期格式
Console.WriteLine(DateTime.Now.ToString("yyyy-M-d HH:mm:ss"));
HTML处理
HTML实体化
using System.Net;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string htmlString = "<h1>Panda Title</h1>";
Console.WriteLine(htmlString);
//<h1>Panda Title</h1>
string encodeHtmlSreing = WebUtility.HtmlEncode(htmlString);
Console.WriteLine(encodeHtmlSreing);
//<h1>Panda Title</h1>
string originHtmlString = WebUtility.HtmlDecode(encodeHtmlSreing);
Console.WriteLine(originHtmlString);
//<h1>Panda Title</h1>
//wait
Console.ReadKey();
}
}
}
URL处理
URL编码
using System;
using System.Net;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string urlString = "https://panda666.com";
Console.WriteLine(urlString);
//https://panda666.com
string encodeUrlSreing = WebUtility.UrlEncode(urlString);
Console.WriteLine(encodeUrlSreing);
//https%3A%2F%2Fpanda666.com
string originurlString = WebUtility.UrlDecode(encodeUrlSreing);
Console.WriteLine(originurlString);
//https://panda666.com
//wait
Console.ReadKey();
}
}
}
切片引用
说明
引用字符串或者数组的一部分,而不是复制一段
使用Span
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16736764.html