Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于检测注释、拆分或子字符串,什么更好_C# - Fatal编程技术网

C# 对于检测注释、拆分或子字符串,什么更好

C# 对于检测注释、拆分或子字符串,什么更好,c#,C#,我试图在C#注释中检测“;”之后的内容 使用Indexof和Substring还是contains和split更好? 如果使用索引,则得到“;”包括后面的所有评论。 如果我使用contains和split,我只得到一条注释,但它的代码行更少 indexComment = 0; indexComment = line.IndexOf(";"); if (indexComment >= 0)

我试图在C#注释中检测“;”之后的内容 使用Indexof和Substring还是contains和split更好? 如果使用索引,则得到“;”包括后面的所有评论。 如果我使用contains和split,我只得到一条注释,但它的代码行更少

            indexComment = 0;
            indexComment = line.IndexOf(";");
            if (indexComment >= 0)
            {
                commands = line.Substring(0, indexComment);
                comment = line.Substring(indexComment);
            }else
            {commands = line;}
VS

两种代码都按预期工作,但您更喜欢什么? 这是我想要检测的示例代码

do something ;this line do something
x+5
;the line above add 5 to x

拆分似乎更好,因为它为您构建了子字符串

只需将Count参数与2相加,因此如果有多个“;”,它们都将包含在您的注释变量中

并使用临时变量,以避免拆分两次

if (line.Contains(";"))
{
    string[] splitLine = line.Split(new char[] { ';' }, 2);
    commands = splitLine[0];
    comment = splitLine[1];
}
else
{ commands = line; }

这两个都不是好答案。解析C#是一个困难的过程,不像查找分号那么容易。
IndexOf
将返回第一次出现的分号,因此使用
substring
只会在第一次出现分号后获取字符串的其余部分
split
在每次出现分号时分离字符串并将其放入数组中。因此,如果注释中有分号,
split
会将这些分号移动到返回数组中的不同位置,您可以始终在从
split
返回的数组上使用
string.join
,忽略数组的第一个索引。请提供一些示例数据和预期结果。例如,您自己发布的代码包含几行,其中第一行的简单检查
错误地检测注释。您最好检查注释的真正开始标记:
/
/*
。但是你仍然需要跳过这些字符串中的文字而不是C#comments,它在C#中的注释检测取决于解析语言的语法@maf您的语言中有字符串/字符文字吗?如果它们可以包含分号,则此操作将失败。如果只使用
;,为什么要创建字符数组
“;”
?@Hawk使用'count'参数需要字符数组。它不会只使用“;”进行编译。如果(line.Contains(“;”)适用于此,则此代码示例本身将失败,因为字符串中的分号将被视为行尾。
if (line.Contains(";"))
{
    string[] splitLine = line.Split(new char[] { ';' }, 2);
    commands = splitLine[0];
    comment = splitLine[1];
}
else
{ commands = line; }