c# 建立字串的技巧


分類

建立時間: 2022年9月17日 17:29
更新時間: 2022年12月17日 01:32

說明

本篇來分享一些好用的建立字串的功能
當你學會之後,你就不用再 + 來 + 去的
最後會附上其他字串的功能,讓大家繼續學習

$ 字串插補

字串插補可以讓你在字串裡面插入變數
使用方法是 $"{variable}"
在雙引號前面加上錢字號,變數放在大括號裡面

string world = "World";

// 常見的串聯兩個字串的作法
Console.WriteLine("Hello " + world);

// 字串插補
Console.WriteLine($"Hello {world}");

預留位置符號

Write()WriteLine() 可以使用 {0} {1} 預留位置符號來替換變數,{0}就是第1個變數,{1}就是第2個變數,依此類推。

string world = "World";

Console.WriteLine("Hello {0}", world);

複合格式字串

當你了解字串插補之後,你可以進一步將變數格式化,再進行字串插補。

本地貨幣

將數字格式化成本地貨幣,錢符號會隨地區自動改變

decimal price = 123.456M;
Console.WriteLine($"Price is {price:c}.");
// Displays "Price is $123.46."

小數格式化

decimal price = 123.456M;
Console.WriteLine($"Price is {price:0.00}.");
// Displays "Price is 123.46."

固定點 (“F”) 格式規範

格式化成浮點數

Example.cs

using System;

public class Program
{
    public static void Main()
    {
        var pi = 3.1415926;
        Console.WriteLine("pi = {0:F}", pi); // pi = 3.14
    }
}

逐字字串常值

當你不想讓字串將反斜線轉義,或者想要換行時,就可以用逐字字串常值
使用方法是 @""
在雙引號前面加上小勞贖

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."

參考

觀看次數: 1225
$@c#interpolationstringverbatim字串插補逐字
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!