一、Substring函數
Substring函數是C#語言中用於截取字元串的函數,它的基本語法如下:
string Substring(int startIndex, int length);
其中startIndex表示截取的起始位置,length表示需要截取的長度。例如:
string str = "Hello World";
string subStr = str.Substring(6, 5); //subStr = "World"
可以看出,subStr的值為”World”,這是因為截取的起始位置為6(從0開始計數,表示W的下標),需要截取的長度為5(Worl)。需要注意的是,如果startIndex+length超過字元串的長度,會引發ArgumentOutOfRangeException異常。
除此之外,Substring函數還有一個重載方法:
string Substring(int startIndex);
這個方法的作用是從startIndex開始截取到字元串的末尾,例如:
string str = "Hello World";
string subStr = str.Substring(6);
//subStr = "World"
二、Split函數
Split函數是C#語言中用於將一個字元串按照指定分隔符分割為多個子字元串的函數。它的基本語法如下:
string[] Split(params char[] separator);
其中separator表示分隔符,可以是單個字元,也可以是多個字元組成的數組。例如:
string str = "apple,banana,orange";
string[] arr = str.Split(',');
//arr = ["apple", "banana", "orange"]
也可以使用特定的分隔符數組:
string str = "apple||banana||orange";
char[] separator = {'|', '|'};
string[] arr = str.Split(separator);
//arr = ["apple", "banana", "orange"]
需要注意的是,如果字元串中不存在分隔符,則Split函數會將整個字元串作為單個元素返回。
三、Remove函數
Remove函數是C#語言中用於刪除字元串中指定字元或子字元串的函數,它的基本語法如下:
string Remove(int startIndex, int count);
其中startIndex表示刪除的起始位置,count表示需要刪除的長度。例如:
string str = "Hello World";
string newStr = str.Remove(5, 1);
//newStr = "Helloorld"
可以看出,newStr的值為”Helloorld”,這是因為刪除了原字元串中的第6個字元(空格),需要注意的是,如果startIndex+count超過字元串的長度,會引發ArgumentOutOfRangeException異常。
除此之外,Remove函數還有一個重載方法:
string Remove(int startIndex);
這個方法的作用是從startIndex開始刪除到字元串的末尾,例如:
string str = "Hello World";
string newStr = str.Remove(5);
//newStr = "Hello"
四、Replace函數
Replace函數是C#語言中用於替換字元串中指定字元或子字元串為另一個字元串的函數,它的基本語法如下:
string Replace(string oldValue, string newValue);
其中oldValue表示被替換的字元串,newValue表示替換成的新字元串。例如:
string str = "I like programming";
string newStr = str.Replace("programming", "coding");
//newStr = "I like coding"
需要注意的是,如果被替換的字元串不存在於原字元串中,則不會發生任何變化。
五、Substring、Split、Remove、Replace函數的綜合應用
以上函數可以結合使用,達到更加高效的處理字元串的目的。例如,將一個包含多個日期的字元串截取、分割、去重、替換,可以如下實現:
string str = "2022-01-01,2022-01-01,2022-01-02,2022-01-03";
string subStr = str.Substring(11); //subStr = "2022-01-01,2022-01-02,2022-01-03"
string[] arr = subStr.Split(','); //arr = ["2022-01-01", "2022-01-02", "2022-01-03"]
arr = arr.Distinct().ToArray(); //arr = ["2022-01-01", "2022-01-02", "2022-01-03"]
string newStr = string.Join(";", arr); //newStr = "2022-01-01;2022-01-02;2022-01-03"
newStr = newStr.Replace("-", "."); //newStr = "2022.01.01;2022.01.02;2022.01.03"
以上代碼完成的功能是:截取了字元串中的日期部分,分隔為多個子字元串,去重,替換日期的分隔符。
原創文章,作者:CZSBP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/343272.html