首页 > 解决方案 > IndexOf 的行为与预期的 C# 不同

问题描述

我有以下三行代码,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);

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

标签: c#stringindexof

解决方案


String.Substring带有 2 个参数的具有下一个签名 -String.Substring(int startIndex, int length)第二个参数是子字符串中的字符数。所以你需要做这样的事情(考虑到你的评论):

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

推荐阅读