0

I am stuck in a convertion of PHP function to C#!

Someone can tell me what I am doing bad?

Original code (PHP):

function delete_all_between($beginning, $end, $string)
{
    $beginningPos = strpos($string, $beginning);
    $endPos = strpos($string, $end);
    if ($beginningPos === false || $endPos === false) {
        return $string;
    }

    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

    return str_replace($textToDelete, '', $string);
}

My code C#:

string delete_all_between(string beginning, string end, string html)
{
    int beginningPos = html.IndexOf(beginning);
    int endPos = html.IndexOf(end);
    if (beginningPos == -1 || endPos == -1)
    {
        return html;
    }
}

I hope someone can help me, I am really stuck!

4
  • What exactly is your problem here? DOes it compile? Do you get errors? Any unexpected results? Commented Jul 4, 2017 at 17:56
  • What's happening that's incorrect? I noticed you're missing the last two lines of code from your PHP function in your C# code. Also, I'll just throw it out there that end is a reserved word in C#. Try rename your end variable to something else. Commented Jul 4, 2017 at 17:58
  • Please read meta.stackoverflow.com/questions/284236/… . We need a clear problem statement (also see minimal reproducible example for guidance). Commented Jul 4, 2017 at 18:34
  • Welcome to SO! Please review the following and edit your question appropriately: stackoverflow.com/help/how-to-ask Commented Jul 4, 2017 at 20:39

1 Answer 1

3

Use Substring and Replace to mask out and replace the unwanted string. Also, I would add a check to make sure that endPos > beginningPos:

string delete_all_between(string beginningstring, string endstring, string html)
{
    int beginningPos = html.IndexOf(beginningstring);
    int endPos = html.IndexOf(endstring);
    if (beginningPos != -1 && endPos != -1 && endPos > beginningPos) 
    {
        string textToDelete = html.Substring(beginningPos, (endPos - beginningPos) + endstring.Length); //mask out
        string newHtml = html.Replace(textToDelete, ""); //replace mask with empty string
        return newHtml; //return result
    }
    else return html; 
}

Test with input

delete_all_between("hello", "bye", "Some text hello remove this byethat I wrote")

Yields the result:

Some text that I wrote

Sign up to request clarification or add additional context in comments.

2 Comments

OP seems to want to return original input unaltered if the validation on the indexes fail.
@Andrew Updated it! Thanks!

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.