根据起始/结束位置从字符串中选择加粗文本

3
在我的ASP.NET页面中,我有一个字符串(从SQL数据库返回)。我想根据给定的文本位置加粗字符串文本的某些部分。
例如,如果我有一个如下所示的字符串:
"This is an example to show where to bold the text"

如果我有一个字符串,并且给我字符的起始位置为6和结束位置为7,那么我将会在该字符串中加粗单词“is”,结果如下所示:
"This is an example to show where to bold the text"
你有什么想法吗?
注意:由于该字符串中可能存在重复的单词,因此必须使用起始/结束位置。

1
你尝试过_任何事情_吗? - Soner Gönül
4个回答

2
你可以使用 String.Replace 方法来实现此功能。

返回一个新字符串,其中当前实例中所有指定的字符串都被替换为另一个指定的字符串。

string s = "This is an example to show where to bold the text".Replace(" is ", " <b>is</b> ");
Console.WriteLine(s);

这里有一个演示

既然你清楚自己想要什么,你可以使用StringBuilder类。

string s = "This is an example to show where to bold the text";
var sb = new StringBuilder(s);
sb.Remove(5, 2);
sb.Insert(5, "<b>is</b>");
Console.WriteLine(s);

这里有一个DEMO
注意:如果你没有看到<b>标签作为输出,那并不意味着它们不存在;)

抱歉我之前没有提到,但我只想加粗指定位置内的文本。例如,如果文本中出现多个单词“is”,我只想加粗指定位置内的文本。 - viv_acious
@highwingers 基于 OP 的示例,它是有效的。你是对的,但问题并不完全清晰。 - Soner Gönül
让我编辑问题 - 我在原始问题中确实指定了起始和结束位置。谢谢。 - viv_acious

2
  1. 在字符串的第7个位置插入一个闭合标签
  2. 在字符串的第5个位置(6-1)插入一个开放标签。
  3. 你将得到一个类似于"This is an example…"的字符串

即从结尾到开头修改字符串(插入标记):

var result = str.Insert(7, "</b>").Insert(6 - 1, "<b>");

1

首先在您的完整字符串中找到要替换的字符串。
<b>+replacestring+</b>替换该字符串

string str="This is an example to show where to bold the text";
string replaceString="string to replace"
str=str.Replace(replaceString,<b>+replaceString+</b>);

编辑 1

string replaceString=str.Substring(6,2);
str=str.Replace(replaceString,<b>+replaceString+</b>);

子字符串示例:
http://www.dotnetperls.com/substring

编辑2

int startPosition=6;
int lastPosition=7;
int lastIndex=lastPosition-startPosition+1;

string str="This is an example to show where to bold the text";
string replaceString=str.Substring(startPosition,lastIndex);
str=str.Replace(replaceString,<b>+replaceString+</b>);

抱歉,我忘了提到可能会有重复的内容,但我只想在指定位置加粗该单词。 - viv_acious
非常感谢你,Shekhar!我很感激。但是我不想加粗单词“is”的多个出现位置(如果它出现了多次)。只有基于开始/结束位置的一个出现位置?这可行吗? - viv_acious

1
您需要像这样做...

**

strStart = MID(str, 0 , 7) ' Where 7 is the START position
str2Replace = "<b>" & MID(str, 8, 10) & "</b>" ' GRAB the part of string you want to replace
str_remain = MId(str, 11, Len(str)) ' Remaining string
Response.write(strStart  & str2Replace & str_remain )

**


谢谢highwingers...我有一个问题 - 我如何在我的ASP.NET c#应用程序中获取MID函数? - viv_acious
哦,我想它被称为子字符串。 - viv_acious
是的,它被称为子字符串,但要小心...子字符串/中间索引从“0”开始,因此您可能需要调整参数。 http://msdn.microsoft.com/zh-cn/library/aka44szs.aspx - highwingers
谢谢 - 我最终使用了一个叫做“插入”的东西,因为它更加简洁。还是非常感谢你的帮助! - viv_acious

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接