c# - Extracting substring based on the same identifier in two locations
问题描述
I found this question, which achieves what I am looking for, however I only have one problem: the "start" and "end" of the substring are the same character.
My string is:
.0.label unicode "Area - 110"
and I want to extract the text between the inverted commas ("Area - 110").
In the linked question, the answers are all using specific identifiers, and IndexOf
solutions. The problem is that if I do the same, IndexOf
will likely return the same value.
Additionally, if I use Split
methods, the text I want to keep is not a fixed length - it could be one word, it could be seven; so I am also having issues specifying the indexes of the first and last word in that collection as well.
解决方案
问题是,如果我这样做,
IndexOf
可能会返回相同的值。
在这种情况下,一个常见的技巧是使用LastIndexOf
找到结束双引号的位置:
int start = str.IndexOf('"');
int end = str.LastIndexOf('"');
if (start >= 0 && end > start) {
// We have two separate locations
Console.WriteLine(str.Substring(start+1, end-start-1));
}
推荐阅读
- java - 已定义的变量返回到未定义的内部订阅
- smtp - 当其凭据通过网络邮件工作时,为什么邮件给出异常为“客户端无权作为此发件人发送”
- .htaccess - TYPO3 将扩展 URL tx_xyz 重写为另一个名称
- python - AttributeError: type object 'PyMongo' has no attribute 'db' with Flask Blueprint Mongodb
- javascript - 保存视频给黑屏
- prolog - 如何在序言中使用 line/2 谓词打印带有输入的行
- java - 多次调用 KeyPressed 事件
- android - Pjsip pjsua2(Android)是否有任何注册监听器?
- debugging - 如何启用 Xbox One 开发者模式激活?
- ios - 在 WebKit 视图中使用自定义代理(ip、端口、登录和密码)