[英]What is the most elegant way to implement GetTextAfterMarker()
這是我C#1天來擁有的另一個舊函數,這是一種更優雅的編寫方式:
//method: gets the text in a string in front of a marker, if marker is not there, then return empty string
//example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "documents"
//example: GetTextAfterMarker("letter043.doc","/") returns ""
//rank:8
public static string GetTextAfterMarker(string line, string marker) {
string r = "";
int pos = line.IndexOf(marker);
if(pos != -1) {
r = line.Substring(pos+(marker.Length),line.Length-pos-(marker.Length));
} else {
r = "";
}
return r;
}
我發現這個名稱有些奇怪,因為它應該返回出現在第一個標記之前的文本。 但是,我認為,這一功能可以完成相同工作(我可以自由更改名稱):
public static string GetTextBeforeMarker(string line, string marker)
{
if (line == null)
{
throw new ArgumentNullException("line");
}
if (marker == null)
{
throw new ArgumentNullException("marker");
}
string result = line.Split(new string[] { marker }, StringSplitOptions.None)[0];
return line.Equals(result) ? string.Empty : result;
}
說明:使用標記作為split參數將字符串分割成一個數組。 如果結果的第一個元素與輸入相同,則標記不在字符串中,因此我們返回一個空字符串,否則返回第一個元素(這是直到標記首次出現的文本)。
我想念什么嗎? 這會更簡單嗎? 我也更喜歡Substring
而不是Split
。
public static string GetTextAfterMarker(string line, string marker) {
int pos = line.IndexOf(marker);
if (pos == -1)
return string.Empty;
return line.Substring(0,pos);
}
您可以使用正則表達式:
public static string GetTextBeforeMarker(string line, string marker)
{
if (String.IsNullOrEmpty(line))
throw new ArgumentException("line is null or empty.", "line");
if (String.IsNullOrEmpty(marker))
throw new ArgumentException("marker is null or empty.", "marker");
string EscapedMarker = Regex.Escape(marker);
return Regex.Match(line, "([^" + EscapedMarker + "]+)" + EscapedMarker).Groups[1].Value;
}
public static string GetTextBeforeMarker(string line, string marker) {
return GetTextAfterMarker(string line, string marker);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.