将函数PHP转换为C#

时间:2017-07-04 17:51:42

标签: c# php code-conversion

我陷入了将PHP函数转换为C#!

有人能告诉我自己做得不好吗?

原始代码(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);
}

我的代码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;
    }
}

我希望有人可以帮助我,我真的被卡住了!

1 个答案:

答案 0 :(得分:3)

使用SubstringReplace屏蔽并替换不需要的字符串。另外,我会添加一项检查以确保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; 
}

使用输入进行测试

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

产生结果:

  

我写的一些文字