簡體   English   中英

將函數PHP轉換為C#

[英]Convert function PHP to 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;
    }
}

希望有人能幫助我,我真的很困!

使用“ Substring和“ Replace掩蓋並替換不需要的字符串。 另外,我將添加檢查以確保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")

產生結果:

我寫的一些文字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM