# Replacing all integers in a string

Let's say I have some expression like,

expr = 1*a + 2*b +3*c + 4*d


I want to write this to a string that I can then use in some other Fortran script. I want all the integers to be of the form "X.0_dp". To do this I can simply do,

StringReplace[
ToString[expr, FortranForm], {"1" -> "2.0_dp", "2" -> "2.0_dp",
"3" -> "3.0_dp", "4" -> "4.0_dp"}]


which works a treat.

Now, is there a way such that I don't have to do this by hand, and generalizes to all integers? e.g. something of the form,

StringReplace[
ToString[expr, FortranForm], {"x" -> "x.0_dp"}]


Thanks for any help

• Does StringReplace[ToString[expr, FortranForm], x : NumberString :> If[StringFreeQ[x, "."], x <> ".0_dp", x <> "0_dp"]] suit your needs? Mar 5, 2019 at 10:07
• Yes that works perfectly! If you submit as an answer I can then mark as accepted :) Further:is there a way to do this for decimals e.g. 0.5 ---> 0.50_dp ? Mar 5, 2019 at 10:11
• Did you try the snippet I gave in that case? Mar 5, 2019 at 10:17
• Ah my bad - all works. Thanks! :) Mar 5, 2019 at 10:20

If you want all integers to be formatted in the same way, you can override the FortranForm formatting of Integer:

Unprotect[Integer];
Format[i_Integer, FortranForm] := Format[
ToString @ i <> ".0_dp",
OutputForm
]
Protect[Integer];


Then:

ToString[1*a + 2*b +3*c + 4*d, FortranForm]

"a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"


If you want to retain the 1 before the a, just use HoldForm to prevent evaluation:

ToString[HoldForm[1*a + 2*b +3*c + 4*d], FortranForm]

"1.0_dp*a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"


Try this:

ToString[(expr /.
Times[x_Integer, y_Symbol] :>
ToString[x, FortranForm] <> ".0_dp " <>
ToString[y, FortranForm]) /. a :> "1.0_dp a"]

(* "1.0_dp a + 2.0_dp b + 3.0_dp c + 4.0_dp d"  *)


Have fun!