获取输入字符串的位置然后获取两端的子字符串

时间:2017-07-19 02:14:58

标签: c# string truncate

我有一个搜索功能,用于搜索文本块中的关键字并显示结果的截断版本。我的问题是,如果搜索关键字接近结尾,它将不会显示搜索关键字。

例如。

Text =“文本块是以某种方式组合在一起的文本,例如在网页上使用段落或块引用。通常,文本采用方形或矩形块的形状”

我用

搜索“时间”
id

它会返回

 text = text.Substring(0, 100) + "...";

有没有办法在搜索关键字之前和之后返回100个字符?

3 个答案:

答案 0 :(得分:2)

你可以这样做,

    string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
    string toBeSearched = "grouped";
    int firstfound = s.IndexOf(toBeSearched);       
    if (firstfound != -1 )
    {
        string before = s.Substring(0 , firstfound);
        string after = s.Substring(firstfound + toBeSearched.Length);         
    }

<强> DEMO

答案 1 :(得分:1)

       string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
       string wordtoSearch = "block";
       int firstfound = s.IndexOf(wordtoSearch);

        // If the index of the first letter found is greater than 100, get the 100 letters before the found word and 100 letters after the found word
        if (firstfound > 100)
        {
            string before = s.Substring(firstfound , firstfound-100);
            string after = s.Substring(firstfound + wordtoSearch.Length, 100);
            Console.WriteLine(before);
            Console.WriteLine(after);
        }
    //// If the index of the first letter found is less than 100, get the letters before the found word and 100 letters after the found word 
        if(firstfound < 100)
        {
            string before = s.Substring(0, firstfound);
            Console.WriteLine(before);
            if(s.Length >100)
            {
            string after = s.Substring(firstfound + wordtoSearch.Length, 100);
            Console.WriteLine(after);
            }
            else
            {
                string after = s.Substring(firstfound + wordtoSearch.Length);
                Console.WriteLine(after);
            }
        }

答案 2 :(得分:0)

您也可以做同样的事情,使其更具可重用性并能够匹配关键字的多个实例

string input = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or blockquotes on a Web page. Often times, the text takes on the shape of a square or rectangular block";
int buffer = 30; // how much do you want to show before/after
string match = "times";

int location = input.IndexOf(match);
while (location != -1) {
    // take buffer before and after:
    int start = location - Math.Min (buffer , location); // don't take before start
    int end = location + match.Length 
            + Math.Min( buffer,  input.Length - location - match.Length); // don't take after end
    Console.WriteLine("..." + input.Substring(start, end-start) + "...");
    location = input.IndexOf(match,location+1);
}

为您提供

的输出
...A block of text is text that is gro...
...with the use of paragraphs or blockquotes on a Web page. Often ...
...pe of a square or rectangular block...