首页 > 解决方案 > 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.

标签: c#.netstring

解决方案


问题是,如果我这样做,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));
}

演示。


推荐阅读