Message Boards Message Boards

1
|
11322 Views
|
4 Replies
|
5 Total Likes
View groups...
Share
Share this post:

How can I parse a string to produce a superscript?

Posted 9 years ago

Hi,

I'm trying to read information from a file and use to label a line in a plot, i.e. If

stringfromfile="abcd"; (* then inside Plot ... *) Epilog->{Text[stringfromfile]}

This works fine for most case, but I don't know how to generate superscripts in this situation, i.e. Read in a string, such as:

stringfromfile="did you know that ^4^He is an interesting isotope" (*I used the "^" here as a arbitrary marker of the superscripted character*)

and parse it such that

Text[stringfromfile]

produces: "did you know that 4He is an interesting isotope". I tried a bunch of approaches, but the closest I got is the following:

tmp = StringSplit[stringfromfile, "^"];
Text[(tmp[[1]] <> ""^tmp[[2]] <> tmp[[3]])];

This produces: "did you know that 4He is an interesting isotope" Does anyone know a way to store / interpret this formatting information, short of generating the BoxData code:

"\<\"did you know that\\!\\(\\*SuperscriptBox[\\(\\\\ \\), \\(4\\)]\\)He is an interesting isotope\"\>"

Thanks

POSTED BY: T Saab
4 Replies
Posted 9 years ago

Hi,

The string structure you are looking for can be obtained using boxes in the following way:

string = (RowBox[{"Did you know that", SuperscriptBox["", 4], "He is an interesting isotope?"}] 
         // DisplayForm)

In case the space between 4 and He appears to be too large, you can modify it either with \[NegativeThinSpace] or with \[NegativeVeryThinSpace]:

string = (RowBox[{"Did you know that", SuperscriptBox["", 4], "\[NegativeVeryThinSpace]", 
                  "He is an interesting isotope?"}] // DisplayForm)

It is also possible to include this extra piece of code directly in the last string for visually different results.

POSTED BY: Xavier Roy

Extending upon Xavier's response, here is a function that replaces every ^nn^ superscript in a string with a Superscript object, and renders it as a Row.

superscriptsToRow[input_] := 
 Row[StringReplace[input, "^" ~~ sup : DigitCharacter .. ~~ "^" :> Superscript["", sup]] /. 
   StringExpression -> List]

superscriptsToRow[stringfromfile]
POSTED BY: Jesse Friedman

Thanks Jesse, this is exactly what I needed

POSTED BY: T Saab

Thanks Xavier.

POSTED BY: T Saab
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract