Bold selective text from string based on start/end position

13,255

Solution 1

  1. Insert a close tag into position 7 of the string
  2. Insert an open tag into position 5 (6 - 1) of the string.
  3. You will get a string like "This is an example…"

I.e. modify string (insert markup) from end to start:

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

Solution 2

You can use String.Replace method for this.

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

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

Here is a DEMO.

Since you clear what you want, you can use StringBuilder class.

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);

Here is a DEMO.

NOTE: Since you didn't see <b> tags as an output, it doesn't mean they are not there ;)

Solution 3

First find the string to replace in your full string.
Replace the string with <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>);

Edit 1

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

SubString Example:
http://www.dotnetperls.com/substring

Edit 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>);

Solution 4

You need to do something like this...

**

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 )

**

Share:
13,255
viv_acious
Author by

viv_acious

Updated on June 29, 2022

Comments

  • viv_acious
    viv_acious almost 2 years

    In my ASP.NET page, I have a string (returned from SQL db). I would like to bold certain part of the string text based on given text position.

    For example, if I have a string as follows:

    "This is an example to show where to bold the text"
    

    And I am given character start position: 6 and end position: 7, then I would bold the word "is" in my string, getting:

    "This is an example to show where to bold the text"

    Any ideas?

    EDIT: Keep in mind I need to use the start/end position as there may be duplicate words in the string.