【问题标题】:IndexOf behaves different than expected C#IndexOf 的行为与预期的 C# 不同
【发布时间】:2020-06-20 22:19:04
【问题描述】:

我有以下三行代码,html 是一个以字符串形式存储的 html 页面。

int startIndex = html.IndexOf("<title>") + 8; // <title> plus a space equals 8 characters
int endIndex = html.IndexOf("</title>") - 18; // -18 is because of the input, there are 18 extra characters after the username.
result = new Tuple<string, bool>(html.Substring(startIndex, endIndex), false);

输入&lt;title&gt;Username012345678912141618&lt;/title&gt; 我希望输出Username。但是,代码找不到&lt;/title&gt;。我不确定出了什么问题。有谁知道什么可能导致这种行为? 我用三个不同的网页(都来自同一个网站)对其进行了测试,并检查了其中的内容。

【问题讨论】:

  • -18?为什么要从 endIndex 中减去 -18?
  • 哦,抱歉,应该将其添加到 OP 中。用户名和 之间总是有 18 个字符的附加文本。像这样:用户名12345678911131517
  • @JasperMW 编辑后问题仍然显示“With the input &lt;title&gt;Username&lt;/title&gt; ...”。那么&lt;title&gt; 你实际测试的是什么?
  • @dxiv 我无法在线发布网站名称,抱歉。它是 用户名 - 站点名称
  • @JasperMW 只需将18 随机字符放在那里。现在写的方式“使用输入 &lt;title&gt;Username&lt;/title&gt; 我希望输出 Username”该行​​直接与您的其他cmets和您刚刚接受的答案相矛盾。

标签: c# string indexof


【解决方案1】:

String.Substring 有 2 个参数有下一个签名 - String.Substring(int startIndex, int length),第二个参数是 the number of characters in the substring。所以你需要做这样的事情(考虑到你的评论):

int startIndex = html.IndexOf("<title>") + 8;
int endIndex = html.IndexOf("</title>")
var result = new Tuple<string, bool>(html.Substring(startIndex, endIndex - startIndex - 18), false);

【讨论】:

  • 嘿伙计,非常感谢!我不需要 de Substring 中的 -18(代码没有它也可以工作),但除此之外这很棒。我觉得自己很愚蠢,因为我阅读了 IndexOf 的文档并假设错误存在。
  • @JasperMW 很乐意提供帮助!
【解决方案2】:

我意识到 OP 正在询问 IndexOf 方法,但这里有一个使用不同方法的解决方案 - 正则表达式,它非常适合“外科手术”从字符串中提取数据。

以下模式是从 html 标记中提取“用户名”所需的全部内容:

var pattern = $@"<title>Username(.+)</title>";

此模式将按如下方式使用:

var pattern = $@"<title>Username(.+)</title>";
var ms = Regex.Match(html, pattern, RegexOptions.IgnoreCase);
var userName = ms.Groups.Count > 0 ? ms.Groups[1].Value : string.Empty;

Regex 的一个优点是您可以使用您正在使用的确切文本来搜索您需要的数据。无需在索引中添加或减去“地点”。

您需要添加:

using System.Text.RegularExpressions;

到你打算实现的类Regex

【讨论】:

    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多