首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 字串操作範例:擷取數字、尋找字元位置與解析檔案路徑 (第 2 部分)

     編輯:關於C語言

1. 擷取字串中的所有數字字元

透過 CharEnumerator 逐字檢查 ASCII 碼 (48-57 為 '0'-'9'):

CharEnumerator ce = textBox1.Text.GetEnumerator();
while (ce.MoveNext())
{
    byte[] arr = Encoding.ASCII.GetBytes(ce.Current.ToString());
    int ascii = arr[0];
    if (ascii >= 48 && ascii <= 57)
        textBox2.Text += ce.Current.ToString();
}
// 輸入 "A23BCDEFG4Hi678" → 輸出 "234678"

2. 找出指定字元在字串中的所有索引位置

string str = textBox1.Text.Trim();
char[] chars = str.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
    if (chars[i].ToString() == textBox2.Text.Trim())
        MessageBox.Show($"字元 '{textBox2.Text}' 在位置 {i}");
}
// 輸入 "aBcdaEFGaHIaaaK", 找 'a' → 0,4,8,11,12,13

3. 解析檔案路徑、檔名與副檔名

string full = textBox1.Text; // 例: C:\gdiplus.dll
string path = full.Substring(0, full.LastIndexOf(@"\"));
string name = full.Substring(full.LastIndexOf(@"\") + 1,
    full.LastIndexOf(".") - full.LastIndexOf(@"\") - 1);
string ext = full.Substring(full.LastIndexOf(".") + 1);

// 輸出: 路徑=C:, 檔名=gdiplus, 副檔名=dll

改進建議

  • 擷取數字:new string(input.Where(char.IsDigit).ToArray()) (LINQ 簡潔)。
  • 尋找索引:for (int i = str.IndexOf(c); i >= 0; i = str.IndexOf(c, i + 1)) 避免逐字轉陣列。
  • 路徑解析:優先使用 System.IO.Path 類別 (GetDirectoryName, GetFileNameWithoutExtension, GetExtension) 跨平台相容。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved