[C#] 字串處理

  • 1158
  • 0

經常開發使用者輸入資訊,在取得使用者從表單輸入值時,有時會希望把輸入值左右空白字串刪除長度等判斷,因此整理以下資訊

空白字串

字串可能為 Null,當在使用Trim(), TrimStart(), TrimEnd() 時可能會產生錯誤,因此較完整寫法為

static void Main(string[] args)
{
	demo(null);
}


public static void demo(string originalValue)
{
	// 如果值是 null,先將它指定為空字串
	if (originalValue == null) 
	{
		originalValue = string.Empty;
	}

	// 如眉上方if判斷Null並修改原始值,
	// 接下來就會因值為 Null 而產生錯誤。
	// NullReferenceException: Object reference not set to an instance of an object.
	string trimLeft = originalValue.TrimStart();
	string trimRight = originalValue.TrimEnd();
	string trimResult = originalValue.Trim();

	Console.WriteLine(trimLeft);
	Console.WriteLine(trimRight);
	Console.WriteLine(trimResult);
}

 長度處裡

計算字串的長度

string account = "abcdefghijklmnopqrstuvwxyz";
// 計算長度
int lengthOfAccount = account.Length;
// 判斷長度是否超過20
if (lengthOfAccount > 20)
{
	Console.WriteLine("帳號最多只能 20 個字,您輸入了" + 				lengthOfAccount + " 個字");
}

string password = "a1234";
// 計算長度
int lengthOfPassword = password.Length;
// 判斷長度是否小於6
if (lengthOfPassword < 6)
{
	Console.WriteLine("密碼必需至少 6 個字,您只輸入了" + lengthOfPassword + " 個字");
}

提醒: 使用 Length之前,記得先判斷字串是不是 null,不是 null 才能叫用。

擷取字串某一對文字

string newsContent = "Curry在例行賽尾聲意外傷到腳,缺席最後12場比賽,季後賽首戰回歸改當替補,上場22分鐘貢獻16分,今天更猛,上半場僅打13分鐘就拿到16分";
// 從0開始擷取10個字
string newsBrief = newsContent.Substring(0, 10); 
Console.WriteLine(newsBrief);

提醒:擷取範圍必須在字串範圍內,不然會產生錯誤。

錯誤訊息:ArgumentOutOfRangeException: Index and length must refer to a location within the string. (Parameter 'length')

 快速產生相同文字字串

string str = "@@@@@@@"; // 太多重複字符,可讀性差
Console.WriteLine(str);

string str2 = new string('@',7); // 明確明白
Console.WriteLine(str2);

比對文字

字串大小寫轉換

string account = "Yuno"; // 有時帳號輸入會大小寫混入
string accountInDatabase = "allen"; // 資料庫裡存放均小寫

// 將輸入字串轉為寫小
string accountInLowercase = account.ToLower();

// ToLower()轉為小寫,ToUpper() 轉為大寫,雖然此判斷可能為後段,前端會有字串是否為空orNull判斷,但後端還是建議也在多加判斷是否為null,確保不會轉換時發生錯誤
if (accountInLowercase == accountInDatabase)
{
	Console.WriteLine("帳號正確");
}
else
{
	Console.WriteLine("帳號錯誤");
}

 字串是否相同

string str1 = "123A";
string str2 = "123A";

// 不好寫法
bool result = str1 == str2;
Console.WriteLine(result);

// 建議用此方法
bool result2 = str1.Equals(str2); 
Console.WriteLine(result2);

進階用法:object references

 字串長度比較

string str1 = "Yuno";
string str2 = "yUNo";
int result = string.Compare(str1, str2, StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine("result:" + result);
// result:0

判斷字串開頭幾個字是不是為特定字串

string url = "http://www.google.com/";
// 判斷 url 開頭是否為 https://
bool isHttps = url.StartsWith("https://"); 

if (isHttps == false)
{
	Console.WriteLine("網址必需是 https:// 開頭, 請修改之後再試一次");
}

string title = "Tips:快速連結到 google 的小技巧";
// 判斷 title 開頭是否為 tips: , 不拘大小寫
bool isTips = title.StartsWith("tips:", StringComparison.CurrentCultureIgnoreCase); 
if (isTips == true)
{
	Console.WriteLine("這是一篇教授技巧的文章");
}

提醒:判斷結尾字串可用EndsWith()。

 StringComparisonm列舉用法:

CurrentCulture 
比較字串時,使用區分文化特性的排序規則和目前的文化特性。

CurrentCultureIgnoreCase 
比較字串時,使用區分文化特性的排序規則和目前的文化特性,並且忽略要比較之字串的大小寫。

InvariantCulture 
比較字串時,使用區分文化特性的排序規則,並且不因文化特性而異。

InvariantCultureIgnoreCase 
比較字串時,使用區分文化特性的排序規則、不因文化特性而異,並且忽略要比較之字串的大小寫。

Ordinal 
比較字串時,使用序數 (二進位) 排序規則。

OrdinalIgnoreCase 
比較字串時,使用序數 (二進位) 排序規則,並且忽略要比較之字串的大小寫。

取得字串在特定字位置

string str = "Hello Word";
int location = sentence.IndexOf("Hello");

if (location < 0)
{
	Console.WriteLine("字串中沒有Hello");
}
else
{
	Console.WriteLine("輸入內容不允Hello");
}

說明:

1. IndexOf() 會傳回第一個符合的位置, 如果第一個字就符合,傳回零; 若完全不符合, 傳回 -1; 因此程式可以利用是否小於零來判斷字串是否包含想找的 char or string(字元或字串)。
2. LastIndexOf() 是從字串最後向前尋找, 傳回第一個符合的位置。
3. IndexOfAny() 尋找字串裡第一個出現的位置,此方法只接收字元(ex:sentence.IndexOfAny(new Char[]{'H','W'}); )。

字串是否包含特定字

string email = "test@icloud.com";
// 判斷字串裡是否包含 icloud,Contains回傳為bool值
bool isIcloud = email.Contains("icloud");
if (isIcloud)
{
	Console.WriteLine("字串裡包含 icloud");
}

 擷取特定字之間的字串

string template = "Goog:2020/12/10;980;down";
// 想取得 980 這個值, 可以先找到第1, 2個分號出現的位置,再將兩個分號之間的字串取出即可

// 第一個分號之後的位置=15,也就是數字出現的位置,+1為所需要的字串第一個位置
int startIndex = template.IndexOf(';')+1; 
// 從15以後,尋找分號再次出現的位置 = 18
int endIndex = template.IndexOf(';', startIndex); 
// 取得兩分號之間共幾個字元
int length = endIndex - startIndex;
string value = template.Substring(startIndex, length);
Console.WriteLine(value);

 替換字串中特定字

string value = "Hello World";
string result = value.Replace("World", "Yuno");
Console.WriteLine(result); // Hello Yuno
// 如果要將以下字串切割可能需要將逗號替換為分號or分號替換成冒號,以利字串切割
string template = "Goog:2020/12/10,980;down";
// 先將逗號replace(置換)成分號, 變成 Goog:2020/12/10;980;down
template = template.Replace(',', ';');
Console.WriteLine(template);
// 接下來可以用分號將每一個資訊切割,並存放在Array(陣列)裡
string[] items = template.Split(';');
foreach (string item in items)
{
    Console.WriteLine(item);
}