c# - 获取输入字符串的位置然后在两端获取子字符串

标签 c# string truncate

我有一个搜索功能,可以在文本 block 中搜索关键字并显示结果的截断版本。我的问题是,如果接近尾声,它不会显示搜索到的关键字。

例如。

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

我用

搜索“时间”
 text = text.Substring(0, 100) + "...";

它会回来

"A block of text is text that is grouped together in some way, such as with the use of paragraphs or..."

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

最佳答案

你可以这样做,

    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

关于c# - 获取输入字符串的位置然后在两端获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179888/

相关文章:

javascript获取斜杠之间的字符

python - 在 Python 中将文本打印到行和列坐标?

sql-server - SQL Server 2008 R2 : Truncate Permissions

php - 如何在 PHP 中截断 UTF8 字符串?

mysql - 如何从 MySQL 中的字符串中获取最后 12 位数字?

c# - List<object>.Contains 表达式树

c# - 使用实体方法的结果通过 lambda 表达式或 linq 查询进行过滤

c# 插件事件处理

C#搜索字符串值以获取缩写的变体

c# - Visual Studio 构建事件条件不相等