iT邦幫忙

2026 iThome 鐵人賽

DAY 8
0
Modern Web

現在就學C# 與 ASP.NET Core系列 第 8 篇

Day 8|String:處理文字資料

  • 分享至 

  • xImage
  •  

Day 7 我們學會使用 Array 管理多筆相同 Type 的資料。

但程式除了數字與集合之外,也經常需要處理:

商品名稱
訂單狀態
使用者輸入
系統訊息

例如:

string product = "TXF";
string status = "Filled";
string message = "Order Completed";

這些文字資料,在 C# 中主要使用:

String(字串)

String 用來表示與處理文字資料。

今天會學到:

  • string
  • char 與 string
  • Index / Length
  • String Interpolation 字串插值
  • 常用 String Method
  • String Immutability

1. String 是什麼?

C# 使用:

string

表示文字資料。

例如:

string product = "TXF";
string status = "Filled";
string message = "Order Completed";

可以拆成:

string      product      "TXF"
  ↓            ↓            ↓
 Type         Name         Value

String 的文字會使用:

" "

雙引號包住。

例如:

string product = "TXF";

所以可以先記住:

文字資料
   ↓
 string

2. char 與 string

Day 4 曾經介紹過:

char side = 'B';
string product = "TXF";

兩者最大的差別:

char
→ 單一字元

string
→ 一段文字

而且使用的引號不同:

char side = 'B';

string product = "TXF";

可以先記成:

'B'
→ char

"TXF"
→ string

3. String 的 Index 與 Length

String 是由一連串字元組成。

例如:

string product = "TXF";

可以看成:

Value      T      X      F
Index      0      1      2

和 Array 一樣,String 使用:

Zero-based Index

所以:

Console.WriteLine(product[0]);
Console.WriteLine(product[1]);
Console.WriteLine(product[2]);

結果:

T
X
F

String Index 取得的是 char

例如:

char firstChar = product[0];

這裡:

product[0]

取得的是:

'T'
↓
char

因為我們取得的是 String 裡面的單一字元。


String Length

String 也可以使用:

.Length

取得字元數量。

例如:

string product = "TXF";

Console.WriteLine(product.Length);

結果:

3

所以:

product.Length
→ 3

當 String 至少有一個字元時,最後一個字元可以透過:

product[product.Length - 1]

取得。

例如:

Console.WriteLine(product[product.Length - 1]);

結果:

F

因此 String 和 Array 有相似的概念:

Array
→ Index / Length

String
→ Index / Length

4. String Interpolation

程式中經常需要把 Variable 放進文字。

例如:

string product = "TXF";
decimal price = 21500.5m;
int quantity = 2;

如果想產生:

Product: TXF, Price: 21500.5, Quantity: 2

可以使用:

String Interpolation(字串插值)

string message =
    $"Product: {product}, Price: {price}, Quantity: {quantity}";

Console.WriteLine(message);

其中:

$
→ 使用 String Interpolation

{ }
→ 放入 Variable 或 Expression

例如:

Console.WriteLine($"Product: {product}");

也可以直接放入 Expression:

Console.WriteLine($"Total: {price * quantity}");

結果:

Total: 43001.0

為什麼使用 String Interpolation?

也可以使用 + 組合文字:

string message =
    "Product: " + product + ", Price: " + price;

但資料一多,可讀性就會下降。

使用 String Interpolation:

string message =
    $"Product: {product}, Price: {price}";

通常會更加清楚。

需要把 Variable 或 Expression 放進文字時,可以優先使用 String Interpolation。


5. 常用 String Method

String 提供許多 Method 用來處理文字。

這些都是 string 提供的 Method。

今天先學會怎麼使用,Day 9 再正式介紹 Method 的結構與運作方式。

初期不需要全部背起來,先認識幾個常用的即可。

Method 用途
Trim() 移除前後空白
ToUpper() 轉成大寫
ToLower() 轉成小寫
Contains() 判斷是否包含文字
Replace() 取代文字

Trim() 與 ToUpper()

假設資料是:

string status = "  filled  ";

可以這樣處理:

string result = status
    .Trim()
    .ToUpper();

Console.WriteLine(result);

結果:

FILLED

流程:

"  filled  "
      ↓
   Trim()
      ↓
   "filled"
      ↓
 ToUpper()
      ↓
   "FILLED"

Method 可以連續使用。

前一個 Method 回傳的結果,可以繼續交給下一個 Method 處理。


ToLower()

ToLower() 可以把文字轉成小寫。

例如:

string product = "TXF";

string result = product.ToLower();

Console.WriteLine(result);

結果:

txf

Contains()

Contains() 用來判斷文字是否包含指定內容。

例如:

string message = "Order Filled";

bool result = message.Contains("Filled");

Console.WriteLine(result);

結果:

True

因為 Contains() 回傳的是:

bool
↓
true / false

所以也可以直接搭配 if:

if (message.Contains("Filled"))
{
    Console.WriteLine("Order Completed");
}

Contains() 會區分大小寫

例如:

string message = "Order Filled";

Console.WriteLine(message.Contains("Filled"));
Console.WriteLine(message.Contains("filled"));

結果:

True
False

所以目前先記住:

Contains() 預設會區分英文大小寫。

之後遇到更完整的文字比較需求,再介紹其他處理方式。


Replace()

Replace() 用來取代文字。

例如:

string status = "Order Pending";

string result = status.Replace("Pending", "Filled");

Console.WriteLine(result);

結果:

Order Filled

而這個例子也會帶出 String 很重要的一個特性:

Immutable


6. String 是 Immutable

String 有一個重要特性:

String 是 Immutable(不可變的)。

例如:

string status = "Pending";

status.Replace("Pending", "Filled");

Console.WriteLine(status);

結果仍然是:

Pending

為什麼?

因為:

status.Replace("Pending", "Filled");

不會直接修改原本的 String。

而是產生一個新的 String:

"Pending"
    ↓
 Replace()
    ↓
"Filled"

如果希望保留新的結果,就需要重新接住:

status = status.Replace("Pending", "Filled");

再輸出:

Console.WriteLine(status);

結果:

Filled

所以可以先記住:

String 是 Immutable,Method 不會直接修改原本的 String。像 Trim()、ToUpper()、Replace() 這類操作會回傳新的 String,因此需要把結果接住。

但不是所有 String Method 都會回傳 String。

例如:

message.Contains("Filled")

回傳的是:

bool

所以 String Method 可能:

處理文字
→ 回傳新的 String

檢查文字
→ 回傳 bool 等其他結果

7. 實際範例:整理訂單資料

把今天學到的內容組合起來。

string product = "  txf  ";
string status = "filled";
decimal price = 21500.5m;
int quantity = 2;

product = product
    .Trim()
    .ToUpper();

status = status
    .Trim()
    .ToUpper();

decimal total = price * quantity;

string message =
    $"Product: {product}, Status: {status}, Total: {total}";

Console.WriteLine(message);

結果:

Product: TXF, Status: FILLED, Total: 43001.0

整個流程:

原始文字
   ↓
Trim()
   ↓
ToUpper()
   ↓
新的 String
   ↓
String Interpolation
   ↓
組合輸出

這個範例結合了前面學過的:

Variable
Operator
String Method
String Interpolation

也可以看出:

原始資料
   ↓
處理資料
   ↓
組合資料
   ↓
輸出結果

Day 8 小結

今天我們解決的問題是:

文字資料要怎麼表示與處理?

答案就是:

String


String

string product = "TXF";

用來表示一段文字。


char 與 string

char
→ 單一字元

string
→ 一段文字

Index / Length

String 和 Array 一樣使用 Zero-based Index:

Value      T      X      F
Index      0      1      2

而:

product.Length

可以取得字元數量。


String Interpolation

$"Product: {product}"

可以把 Variable 或 Expression 放進文字。


String Method

常見操作:

Trim()
ToUpper()
ToLower()
Contains()
Replace()

這些 Method 可以用來:

處理文字
或
檢查文字

目前不需要全部背起來,需要時再查即可。


String Immutability

最重要的是:

String 是 Immutable,不會直接修改原本的文字。

例如:

status = status
    .Trim()
    .ToUpper();

Trim() 與 ToUpper() 會回傳新的 String,因此要把結果重新接住。


上一篇
Day 7|Array:管理多筆相同 Type 的資料
下一篇
Day 9|Method:把程式邏輯整理成可以重複使用的功能
系列文
現在就學C# 與 ASP.NET Core 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言