开发者

Why isn't this C# code working? It should return the string between two other strings, but always returns an empty string

开发者 https://www.devze.com 2023-04-08 07:37 出处:网络
The title explains it all.It seems simple enough, so I must be overlooking something stupid.Here\'s what I\'ve got.

The title explains it all. It seems simple enough, so I must be overlooking something stupid. Here's what I've got.

    private string getBetween(string strSource, string strStart, string strEnd)
    {
        int start, end;
        if (strSource.Contains(s开发者_如何转开发trStart) && strSource.Contains(strEnd))
        {
            start = strSource.IndexOf(strStart, 0) + strStart.Length;
            end = strSource.IndexOf(strEnd, start);
            return strSource.Substring(start, end - start);
        }
        else
        {
            return "";
        }
    }

Thanks, guys.


Your code doesn't make sure that start and end are in order.

static string SubString(string source, string prefix, string suffix)
{
    int start = source.IndexOf(prefix); // get position of prefix
    if (start == -1)
        return String.Empty;
    int subStart = start + prefix.Length; // get position of substring
    int end = source.IndexOf(suffix, subStart); // make sure suffix also exists
    if (end == -1)
        return String.Empty;
    int subLength = end - subStart; // calculate length of substring
    if (subLength == 0)
        return String.Empty;
    return source.Substring(subStart, subLength); // return substring
}


As couple of peoples said the problem that you code is working on very specific input, it's all because of this start and end IndexOf magic =) But when you try to update you code to work correct on more inputs you will get into problem that your code become very long with many indexes, comparsions, substrings, conditions and so on. To avoid this i like to recommend you use regular expressions with theirs help you can express what you need on special language.

Here is the sample which solves your problem with regular expressions:

        public static string getBetween(string source, string before, string after)
        {
            var regExp = new Regex(string.Format("{0}(?<needle>[^{0}{1}]+){1}",before,after));
            var matches = regExp.Matches(source).Cast<Match>(). //here we use LINQ to
                OrderBy(m => m.Groups["needle"].Value.Length).  //find shortest string
                Select(m => m.Groups["needle"].Value);          //you can use foreach loop instead
            return matches.FirstOrDefault();
        }

All tricky part is {0}(?<needle>[^{0}{1}]+){1} where 0 - before string and 1 - after string. This expression means that we nned to find string that lies beetween 0 and 1, and also don't contains 0 and 1.

Hope this helps.


I get the correct answer if I try any of these:

var a = getBetween("ABC", "A", "C");
var b = getBetween("TACOBBURRITO", "TACO", "BURRITO");
var c = getBetween("TACOBACONBURRITO", "TACO", "BURRITO");

The problem is likely with your input argument validation, as this fails:

var a = getBetween("ABC", "C", "A");
var a = getBetween("ABC", "C", "C");

You can improve your validation of the issue by writing some test cases like these as a separate fixture (xUnit, or main loop in throw away app).

0

精彩评论

暂无评论...
验证码 换一张
取 消