2017-07-04 61 views
0

我被困在PHP函数转换为C#!将函数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; 
    } 
} 

我希望有人能帮助我,我很坚持!

+0

这里你的问题到底是什么?是否编译?你有错误吗?任何意外的结果? – HimBromBeere

+0

发生了什么事不正确?我注意到你错过了C#代码中PHP函数的最后两行代码。另外,我只是把它放在那里,'end'是C#中的一个保留字。尝试重命名你的最​​终变量为别的东西。 – RToyo

+0

请阅读\t https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question。我们需要明确的问题陈述(另请参见[mcve])。 – GhostCat

回答

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") 

生成结果:

一些文字,我写

+0

如果对索引的验证失败,OP似乎希望返回原始输入不变。 – Andrew

+0

@Andrew更新了它!谢谢! – Max