Table of Contents
<span class="ez-toc-title-toggle"><a href="#" class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" aria-label="顯示/隱藏內容目錄"><span class="ez-toc-js-icon-con"><span class=""><span class="eztoc-hide" style="display:none;">Toggle</span><span class="ez-toc-icon-toggle-span"><svg style="fill: #999;color:#999" xmlns="http://www.w3.org/2000/svg" class="list-377408" width="20px" height="20px" viewBox="0 0 24 24" fill="none"><path d="M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z" fill="currentColor"></path></svg><svg style="fill: #999;color:#999" class="arrow-unsorted-368013" xmlns="http://www.w3.org/2000/svg" width="10px" height="10px" viewBox="0 0 24 24" version="1.2" baseProfile="tiny"><path d="M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z"/></svg></span></span></span></a></span>
刪除字串左邊, 右邊, 兩側的空白
- TrimStart() 刪除左空白
- rimEnd() 刪除右空白
- Trim() 刪除左右空白
範例:
string str_name = " bocky Bocky ";
string trim_start = str_name.TrimStart();
string trim_end = str_name.TrimEnd();
string trim_reim = str_name.Trim();結果如下:
bocky Bocky
bocky Bocky
bocky Bocky獲得字串的長度
最常使用在獲得帳號或密碼的長度上,做長度的限制。
string password = "iambocky";
int password_len = password.Length;
Console.WriteLine("密碼長度:" + password_len); // 8截取字串
- 擷取的位置需在字串範圍
string name = "iambocky";
string news_name = name.Substring(3, 5);
Console.WriteLine(news_name);字串出現某些字的位置
- IndexOf() 由左至右開始檢查,傳回第一個符合的位置,若字串中沒有符合則傳回-1
- LastIndexOf() 是從字串最後(右向左)尋找, 傳回第一個符合的位置
範例:判斷字串裡是否有@
string email = "bocky@gmail.com";
int location = email.IndexOf('@');
Console.WriteLine(location); // @所在的位置(從0開始)
if (location > 0)
{
Console.WriteLine("屬於email");
}
else
{
Console.WriteLine("不屬於email");
}字串取代
將字串裡的某一個字,或某個字串, 置換成其他字。
不想要空白,就把空白取代為,範例:
string value = " te st .jos n ";
string result = value.Replace(" ", "");
Console.WriteLine(result); // test.josn字串切割
將一個字串分割成數個子字串。
Split()
舉例要取年月日,用/來做切割,切割出來的資料需存在陣列內。
string today = "2021/10/31";
string[] tmp = today.Split('/');
string year = tmp[0];
string month = tmp[1];
string day = tmp[2];
Console.WriteLine(year); // 2021
Console.WriteLine(month); // 10
Console.WriteLine(day); //31字串轉換
- ToUpper() 全部大寫
- ToLower() 全部小寫
大部分需要全部轉換成大小寫一致的話是為了比對。
string name = "Bocky";
Console.WriteLine(name.ToUpper()); //全部大寫BOCKY
Console.WriteLine(name.ToLower()); //全部小寫bocky補充:
若想判斷二個變數內的字串文字是否相同, 建議使用:Equals() 判斷字串開頭或結尾是否符合指定的字串
傳回:Boolean
範例:檢查開頭是否有https://
string url = "https://www.quietbo.com";
bool is_https = url.StartsWith("https://");範例:檢查結尾是否有.com
string url = "https://www.quietbo.com";
bool is_com = url.EndsWith(".com");