c# - 在数组中查找文本

标签 c#

我正在将例程从 C++ 移植到 C#,但很难理解移植失败的原因:

我有一个字符串数组,其中包含我正在尝试删除的内容。

    string[] aryLines = File.ReadAllLines(mstrFilename);

数组包含以下内容:

aryLines = new[]
{
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
    "<!--",
    "",
    "  File:\t\tuif.xml, User Interface",
    "  Notes:\tThis file contains the application layout and includes",
    "\t\tfor other files defining the application look and functionality.",
    "",
    "  Node:\t\tuif, Root container node",
    "  Attributes:\tid\t\t: Unique node identifier",
    "\t\tcameras\t\t: Initial camera set-up",
    " \t\tcolor_bg\t: Application background colour:",
    "\t\t\t\t\tAlpha, Red, Green, Blue",
    "\t\theight\t\t: Height of the application container",
    "\t\twidth\t\t: Width of the appplication container\t\t",
    "",
    "  Node:\t\tinclude, Includes another XML file",
    "  Attributes:\tname\t\t: Encoded path to XML file to include",
    "",
    "  History:\t2017/09/11 Created by Simon Platten",
    "// -->"
};

我有一个方法应该删除评论,发现第一次出现 <!--和匹配的 --> ,然后它将删除中间的所有内容。问题是,虽然它找到了 <!--它找不到 -->我不明白为什么。

private static readonly string msrostrCmtClose = "-->";
private static readonly string msrostrCmtOpen = "<!--";

int intOpen = 0;
while((intOpen = Array.IndexOf(aryLines, msrostrCmtOpen, intOpen)) >= 0) 
{
    //Opening marker located, look for closing marker   
    int intClose = Array.IndexOf(aryLines, msrostrCmtClose, intOpen);

    if ( intClose < intOpen ) 
    {
        //Shouldn't get here!
        continue;
    }

    Console.WriteLine(intOpen);
}

上面的例程不完整,但是在调试器里看intClose一直是-1,为什么?

最佳答案

这里的问题是 Array.IndexOf 将每个元素与您要查找的内容进行比较,只是您要查找的内容实际上并不在数组中。数组中的内容是 //--> 而不仅仅是 -->

您可以做的是创建一个像这样的简单函数:

private int IndexOfInArray(string[] array, string elemToFind, int startIndex = 0)
{
    for (int i = startIndex; i < array.Length; i++)
    {
        if (array[i].Contains(elemToFind))
            return i;
    }

    return -1;
}

然后像这样使用它:

int intOpen = 0;
while((intOpen = IndexOfInArray(aryLines, msrostrCmtOpen, intOpen)) >= 0 ) 
{
    //Opening marker located, look for closing marker   
    int intClose = IndexOfInArray(aryLines, msrostrCmtClose, intOpen);
    if (intClose < intOpen) 
    {
        //Shouldn't get here!
        continue;
    }

    Console.WriteLine(intOpen);
}

您可能必须将 intOpen 设置为 intClose 或只是 intOpen++ 才能永远得到相同的结果。

关于c# - 在数组中查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876161/

相关文章:

c# - ToolStripDropDown 列表的水平分隔符

c# - DDD : what are the OOP alternatives for procedural Application Services?

c# - 从 Controller 发送颜色十六进制到 View 而不带引号变成“?

c# - 滚动 X 轴绘图区 - Silverlight 列系列

C#:处理 WebClient "protocol violation"

c# - ASP.NET Core 2 中的 Startup.cs 与 Program.cs

c# - 我的代码是否展示了良好的 WPF 实践?

c# - 为什么 String.Split() 不允许单个字符串作为参数

c# - 在具有通配符 Equatability 的类上实现 GetHashCode

c# - Visual Studio 2019 intellisense 在每个非 .NET 命名空间下显示红色波浪线