0

I need to delete a substring in a string. I need to remove a string starting from a particular character until another character. This is my code:

    [Test]
    public static void TestDeleteSign()
    {
        var s = "РасчНал[]{@ТипНП}/РасчНалГруп[]{@СубРФ}/@ДоляНалБаз";
        var result = DeleteSignature(s);
        var acceptResult = "РасчНал/РасчНалГруп/@ДоляНалБаз";
        Assert.AreEqual(acceptResult, result);
    }
    public static string DeleteSignature(string s)
    {
        if (s.Contains("[]{"))
        {
            var firstEntry = s.IndexOf("[]{");
            var closeEntry = s.IndexOf('}');
            s = s.Remove(firstEntry, closeEntry - firstEntry + 1);
            DeleteSignature(s);
        }
        return s;
    }

The result is:

Expected: "РасчНал/РасчНалГруп/@ДоляНалБаз"
But was: "РасчНал/РасчНалГруп[]{@СубРФ}/@ДоляНалБаз"
14
  • 12
    Hint: a statement of DeleteSignature(s); isn't going to do anything useful, because you're not using the return value... Commented May 24, 2016 at 13:59
  • 2
    Try it with s = DeleteSignature(s); Commented May 24, 2016 at 14:02
  • 1
    @HenkHolterman you spoilt the fun :( Commented May 24, 2016 at 14:03
  • 2
    @CarbineCoder - we're not supposed to have fun here (anymore). Anyway, it's a beginner question but very well asked. Anyone who puts Actual and Expected results in a question deserves some encouragement. Commented May 24, 2016 at 14:05
  • 1
    @HenkHolterman Except they hadn't originally, that was edited in by someone else after someone prompted them with a comment Commented May 24, 2016 at 14:06

1 Answer 1

4

Your function returns a string. After the first iteration of your function, your function is called a second time. Regardless of what happens there, your code will only return one passage removed as you do nothing with your recursive execution of DeleteSignature(s). You need to return the output of your recursive execution like:

public static string DeleteSignature(string s)
{
    if (s.Contains("[]{"))
    {
        var firstEntry = s.IndexOf("[]{");
        var closeEntry = s.IndexOf('}');
        s = s.Remove(firstEntry, closeEntry - firstEntry + 1);
        return DeleteSignature(s);
    }
    return s;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the mistake OP made was thinking that reassigning s's reference would affect the object elsewhere, but that reference variable to s in each instance of DeleteSignature is independent of the other references to the same object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.