# Change parentheses to square-brackets when using CForm

I'm not experienced with Mathematica, but am learning to appreciate its awesome power for manipulations.

I get the an expression like this when using CForm (I cut it short to simplify):

T(0, 0) + ht*((-((T(-1, 0) + T(0, 0))*u(-0.5, 0))


In Mathematica, T, u are functions. But they should be arrays in my C code. Can I tell Mathematica that when it is exporting T, u to C, it should treat them as arrays and use []?

Update: I haven't written any C in a long while, so I forgot its syntax for multidimensional arrays, i.e. array[first][second]! Here is the amended code:

ToString[CForm[t[12, 156] + ht u[5, 3]]]

StringReplace[%, {
"t(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "t[" ~~ a ~~ "][" ~~ b ~~ "]",
"u(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "u[" ~~ a ~~ "][" ~~ b ~~ "]"
}]

(* Out: "t + ht*u" *)


Original answer: If it is acceptable to you to deal with strings for your C code, you could convert to a string, then apply a string pattern:

ToString[CForm[t[12, 156] + ht u[5, 3]]]

StringReplace[%,
{
"t(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "t[" ~~ a ~~ "," ~~ b ~~ "]",
"u(" ~~ Shortest[a__] ~~ "," ~~ Shortest[b__] ~~ ")" -> "u[" ~~ a ~~ "," ~~ b ~~ "]"
}
]

(* Out: "t[12,156] + ht*u[5,3]" *)


The Shortest[a__] forms are there to handle cases in which the arguments to the functions are longer than one character.

• thanks for the input. However, this seems to not work more generally: If I throw in a few exta parentheses inside what I want to become square-brackets, Mathematica gets the pattern wrong. – Yair Daon May 10 '15 at 19:14

Mathematica's CForm will convert Part expressions to arrays, so you can achieve what you want by changing your functions to Part expressions:

ReplaceAll[
HoldForm[T[0,0]+ht (-(T[-1,0]+T[0,0]) u[-.5,0])],
{T[a_,b_]:>T[[a,b]], u[a_,b_]:>u[[a,b]]}
] //CForm


T + ht*(-(T[-1] + T)*u[-0.5])

Another possibility is to teach CForm about your functions:

Format[T[a_, b_], CForm] := HoldForm[T[[a, b]]]
Format[u[a_, b_], CForm] := HoldForm[u[[a, b]]]


T[0,0]+ht (-(T[-1,0]+T[0,0]) u[-.5,0]) //CForm