实现GetTextAfterMarker()的最优雅方式是什么?

时间:2009-07-23 14:10:52

标签: c# string refactoring

这是我从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;
}

4 个答案:

答案 0 :(得分:1)

我觉得这个名字有点奇怪,因为它应该在第一个标记之前返回出现的文字。但是这个人做同样的工作,我想(我冒昧改变了名字):

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参数将字符串拆分为数组。如果结果的第一个元素与输入相同,则标记不在字符串中,因此我们返回一个空字符串,否则我们返回第一个元素(这是第一次出现的标记之前的文本)。

答案 1 :(得分:1)

我错过了什么吗?这不是更简单吗?我也更喜欢SubstringSplit

public static string GetTextAfterMarker(string line, string marker)  {
    int pos = line.IndexOf(marker);
    if (pos == -1)
       return string.Empty;
    return line.Substring(0,pos);
}

答案 2 :(得分:0)

您可以使用正则表达式:

    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;
    }

答案 3 :(得分:0)

public static string GetTextBeforeMarker(string line, string marker)  {
    return GetTextAfterMarker(string line, string marker);
}