c# - 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>
. 我不确定出了什么问题。有谁知道什么可能导致这种行为?我用三个不同的网页(都来自同一个站点)对其进行了测试,我检查了其中的内容。
解决方案
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);
推荐阅读
- javascript - Firebase Web 身份验证不起作用 - 仅针对键入错误的电子邮件返回错误
- ios - React Pwa IOS - 在第二次启动时,应用程序卡在加载中
- javascript - 如何连接超链接的变量?
- html - 辅助功能问题选择带有空格键的复选框会跳过内容
- kubernetes - Monorepo 中包含许多包的条件云构建
- python - 如何从 x 到 y 的列表中删除?
- sql - 使用 SQL 比较两列,以确保两者中都存在相同的一组值
- python - 如何在全局变量上使用 __get__()?
- java - 随机化单选组中的单选按钮
- haskell - Haskell:安装 pureMD5 包