簡體   English   中英

C#從/ ** /之間的字符串中刪除字符

[英]C# Remove characters from string between /**/

在字符串中將是這樣的:

for(I=1;I<10;I++) /*Else*/ {A = "for"; B = 'c'; break;} // while(a < 10)

我想從這個字符串任何介於刪除/**/之間""之間''后什么//

這是例子

輸入:

for(I=1;I<10;I++) /*Else*/ {A = "for"; B = 'c'; break;} // while(a < 10)

輸出:

FOR(i=1;i<10;i++) /**/ {a = ""; b = ''; BREAK;} // 

我知道我必須使用以下字符串:

for (int i = 0; i < input.Length; i++)
{
    // search for /**/ ?
}

但我不知道該如何刪除字符並將其他字符放入新字符串中。

string sentence = "for(I=1;I<10;I++) /*Else*/ {A = "for"; B = 'c'; break;} // while(a < 10)";
        //how can I remove these characters from string so it will look something like this?
string shortSentence = "FOR(i=1;i<10;i++) /**/ {a = ""; b = ''; BREAK;} //";

嘗試這個。 這個想法是首先刪除最后的內容,即//注釋。 然后,我們搜索/ *和下一個/,刪除該文本(剩下/**/ ,保存該字符串的索引,並將其也刪除。一旦沒有更多/字符串,我們就重新插入/**/進入我們從中刪除的職位。

注意:如果您有類似/* comment /* more comment */ and some other part */則此方法將無效。 但這在C#中也不是有效的注釋,這是您在此處標記的語言。

 static string s = "for(int i = 0; i < 10; i++){ var myVar = \"Test\"; /*commented out code*/ Console.WriteLine(\"stuff\"); /* more comments here*/}//my comments here \n var myOverVar = /*more stuff removed*/ true; //some more comments";


static void Main(string[] args)
{
    //s.IndexOf()
    var result = new List<string>();
    var lines = s.Split(new[] {"\n"}, StringSplitOptions.RemoveEmptyEntries); //use this if you have multiple code lines, separated by new lines.
    foreach (var line in lines)
    {
        var listOfPositions = new List<int>();
        var l = line;
        //chop off everything after comments
        var indexOfLineComment = l.IndexOf("//");

        l = l.Remove(indexOfLineComment + 2); // 2 because // is two characters long
                var openBraceIndex = l.IndexOf("/*");
        while (openBraceIndex != -1) //-1 indicates that we didn't find /*
        {
            var closingBraceIndex = l.IndexOf("*/");
            if (closingBraceIndex == -1)
            {
                break; //you didn't specify how to the case when an error in syntax was made, but handle it here
            }
            l = l.Remove(openBraceIndex + 2, closingBraceIndex - openBraceIndex-2);
            var ind = l.IndexOf("/**/");
            listOfPositions.Insert(0, ind);
            l = l.Remove(ind, 4);
            openBraceIndex = l.IndexOf("/*");

        }
        foreach (var i in listOfPositions)
            if (l.Length <= i)
                l = l + "/**/";
            else
                l = l.Insert(i, "/**/");
        result.Add(l);
    }

}

暫無
暫無

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

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