C#實(shí)現(xiàn)字符串格式化的示例代碼
寫(xiě)在前面
在日常編程中,經(jīng)常需要對(duì)字符串進(jìn)行格式化操作,以便呈現(xiàn)為不同的格式,滿足各種各樣的顯示需求,C#的字符串格式化參數(shù)是非常豐富的,這里做個(gè)簡(jiǎn)單的列舉,以供后續(xù)參考和延伸。
代碼實(shí)現(xiàn)
var currentTime = DateTime.Now; Console.WriteLine($"{currentTime:yyyy年MM月dd日 HH時(shí):mm分:ss秒:ffff毫秒}"); // 日期格式化 Console.WriteLine(currentTime.ToString("yyyy-MM-dd HH:mm:ss:ffff")); Console.WriteLine($"{currentTime:D}"); Console.WriteLine($"{currentTime:d}"); Console.WriteLine($"{currentTime:F}"); Console.WriteLine($"{currentTime:f}"); Console.WriteLine($"{currentTime:G}"); Console.WriteLine($"{currentTime:g}"); Console.WriteLine($"{currentTime:m}"); Console.WriteLine($"{currentTime:T}"); Console.WriteLine($"{currentTime:t}"); var left = "left"; var right = "right"; Console.WriteLine($"Span:{left,-20}|{right,20}"); // 左右對(duì)齊 Console.WriteLine($"Span:{left,-20}|{right,20}"); Console.WriteLine($"Span:{left,-20}|{right,20}"); var holder01 = "{holder01}"; var holder02 = @"\{holder02}"; Console.WriteLine($"holder01:{{{holder01}}}"); Console.WriteLine($"holder01:{{{holder02}}}"); var sex = 0; Console.WriteLine($"{(sex == 0 ? "Male" : "Female")}"); // 表達(dá)式需要用()包起來(lái) string? value = null; Console.WriteLine($"value is {(value ?? "test value")}"); // 表達(dá)式需要用()包起來(lái) var ob = new { name = "Lee", age = 11 }; Console.WriteLine($"name: {ob.name}, age: {ob.age}"); // 對(duì)象成員格式化 long num = 123456; Console.WriteLine($"{num:D8}"); // 格式化成8位的十進(jìn)制 Console.WriteLine($"{num:N2}"); // 格式化成保留2位小數(shù)并用千分位符號(hào)隔開(kāi)的字符串 Console.WriteLine($"{num:C3}"); // 格式化成貨幣小數(shù)點(diǎn)保留3位 Console.WriteLine($"{num:X000}"); // 格式化成十六進(jìn)制 Console.WriteLine($"{0.19:P}"); // 格式化百分比 Console.WriteLine($"{0.19:P1}");
執(zhí)行結(jié)果
到此這篇關(guān)于C#實(shí)現(xiàn)字符串格式化的示例代碼的文章就介紹到這了,更多相關(guān)C#字符串格式化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
WPF實(shí)現(xiàn)列表分頁(yè)控件的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用WPF實(shí)現(xiàn)列表分頁(yè)控件,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2022-10-10C#中按引用傳遞與按值傳遞的區(qū)別,以及ref與out關(guān)鍵字的用法詳解
以下是對(duì)C#中按引用傳遞與按值傳遞的區(qū)別,以及ref與out關(guān)鍵字的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-07-07C#中標(biāo)準(zhǔn)的IDispose模式代碼詳解
在本篇文章中小編給大家分享的是關(guān)于C#中標(biāo)準(zhǔn)的IDispose模式的實(shí)例用法相關(guān)內(nèi)容,有需要的朋友們測(cè)試下。2019-09-09c# 實(shí)現(xiàn)MD5,SHA1,SHA256,SHA512等常用加密算法源代碼
c# 如何實(shí)現(xiàn)MD5,SHA1,SHA256,SHA512等常用加密算法,需要的朋友可以參考下2012-12-12Unity的AssetPostprocessor之Model函數(shù)使用實(shí)戰(zhàn)
這篇文章主要為大家介紹了Unity的AssetPostprocessor之Model函數(shù)使用實(shí)戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08