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

C# 常用核心 API 速查手冊:日期、字符串、編碼、Web 操作全攻略

     編輯:關於C語言

前言

本文匯總 Visual C# 開發中高頻使用的核心函數與方法,涵蓋日期時間處理、類型轉換、字符串操作、編碼轉換、Web 常用操作、XML 處理、字符判斷等實用技巧,旨在為開發者提供快速查閱的參考手冊。

一、DateTime 日期時間處理

// 獲取當前時間
DateTime currentTime = DateTime.Now;

// 1.1 完整年月日時分秒
// currentTime = DateTime.Now; // 已在上方獲取

// 1.2-1.8 單獨獲取各部分
int year = currentTime.Year;
int month = currentTime.Month;
int day = currentTime.Day;
int hour = currentTime.Hour;
int minute = currentTime.Minute;
int second = currentTime.Second;
int millisecond = currentTime.Millisecond;

// 1.9 中文完整日期時間(不含秒)
string strFull = currentTime.ToString("f"); // 如:2024年1月15日 14:30

// 1.10 中文年月
string strYM = currentTime.ToString("y"); // 如:2024年1月

// 1.11 中文月日
string strMD = currentTime.ToString("m"); // 如:1月15日

// 1.12 短日期格式 (yyyy-M-d)
string strYMD = currentTime.ToString("d"); // 如:2024-1-15

// 1.13 短時間格式 (HH:mm)
string strTime = currentTime.ToString("t"); // 如:14:30

二、類型轉換核心方法

字符串轉數值

// Int32.Parse - 字符串轉 32 位整數
int num1 = Int32.Parse("12345");
int num2 = Int32.Parse(strVariable);

數值/對象轉字符串

.ToString() // 基礎轉換

// 格式化輸出示例 (以 12345 為例)
12345.ToString("n"); // "12,345.00" - 數字格式
12345.ToString("C"); // "¥12,345.00" - 貨幣格式
12345.ToString("e"); // "1.234500e+004" - 科學記數法
12345.ToString("f4"); // "12345.0000" - 固定小數位
12345.ToString("x"); // "3039" - 十六進制
12345.ToString("p"); // "1,234,500.00%" - 百分比格式

三、字符串核心操作

長度獲取

string str = "中國";
int len = str.Length; // 返回字符數 (此處為 2)

編碼轉換與字節操作

// 字符串轉字節數組 (默認編碼)
byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
int byteLen = bytes.Length; // 字節長度

高效字符串拼接:StringBuilder

// 避免頻繁使用 + 運算符產生大量臨時對象
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("中華");
sb.Append("人民");
sb.Append("共和國");
string result = sb.ToString(); // "中華人民共和國"

子串提取

// Substring(起始索引, 長度) - 索引從 0 開始
string s1 = str.Substring(0, 2); // 從第 0 位取 2 個字符

字符串查找與定位

// 首次/最後一次出現位置
str.IndexOf("字");           // 查找字符首次位置
str.IndexOf("字串");         // 查找子串首字符位置
str.IndexOf("字串", 3, 2);   // 從索引 3 開始,查找 2 個字符範圍內的子串

// 反向查找
str.LastIndexOf("字");

插入與填充

// Insert(索引, 字符串) - 在指定位置插入
str.Insert(1, "字"); // "中字國"

// PadLeft/PadRight(總長度, 填充字符) - 左/右填充至指定長度
str.PadLeft(10, '1'); // "1111111中國人" (長度 10)
str.PadRight(10, '*'); // 右側填充 *

刪除與替換

// Remove(起始索引, 長度) - 刪除指定範圍字符
// Replace(舊值, 新值) - 替換所有匹配項
string str = "中國";
str = str.Replace("國", "央"); // "中央"

// 實用防腳本注入:將 < 替換為無害實體
string input = "這是
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved