1

How can I colorize letters in the given string?

For instance:

string = "jaonvtaqhsy"

How to colorize 3 letters in the middle of string (e,g, "vta")?

I tried:

Split the given string in the three parts

a=StringTake[string, {1, 4}]
b=StringTake[string, {5, 7}]
c=StringTake[string, {8, 11}]

and then colorize each string

aa = Style[a, Blue, Bold]
bb = Style[b, Red, Bold]
cc = Style[c, Blue, Bold]

then join them back together

StringJoin[aa,bb,cc]

or

aa <> bb <> cc

but there is an error message

enter image description here

David G. Stork
  • 41,180
  • 3
  • 34
  • 96
vito
  • 8,958
  • 1
  • 25
  • 67

2 Answers2

1
string = "jaonvtaqhsy"; 
a = StringTake[string, {1, 4}];
b = StringTake[string, {5, 7}];
c = StringTake[string, {8, 11}];
aa = Style[a, Blue, Bold]; 
bb = Style[b, Red, Bold]; 
cc = Style[c, Blue, Bold]; 
ToString[#1, FormatType -> StandardForm] & @ Row[{aa, bb, cc}]

produces a colored string.

Rolf Mertig
  • 17,172
  • 1
  • 45
  • 76
1
highlight[mystring_String, where_List] :=

 Row@{StringTake[mystring, {1, where[[1]] - 1}], 
      Style[StringTake[mystring, where], Red], 
      StringTake[mystring, {where[[2]] + 1, StringLength[mystring]}]}

highlight["abcdefghijkl", {3, 5}]

If you want to highlight a single character,

highlight["abcdefghijkl", {3, 3}]
David G. Stork
  • 41,180
  • 3
  • 34
  • 96