Less Ugly way to concatenate strings

I have been working on a plotting library in mojo that is based on gnuplot. The code works but the string parts are extremely ugly:
...
fn plotArray(inout self, *data: Float32, lineType:Int32=0, lineColor:Int32=7, title:String="Plot") raises:
with open("m1v1tf01_temp.dat", "w") as f:
var string: String = ""
for dat in data:
string += FloatToString(dat) + ",\n"
f.write(string)
self.gnuplot_gateway.callGNUPlotCommand("plot \"m1v1tf01_temp.dat\" title " + title + " lt " + IntToString(lineType) + " lc " + IntToString(lineColor)) # <<< Ugly strings
...
...
fn plotArray(inout self, *data: Float32, lineType:Int32=0, lineColor:Int32=7, title:String="Plot") raises:
with open("m1v1tf01_temp.dat", "w") as f:
var string: String = ""
for dat in data:
string += FloatToString(dat) + ",\n"
f.write(string)
self.gnuplot_gateway.callGNUPlotCommand("plot \"m1v1tf01_temp.dat\" title " + title + " lt " + IntToString(lineType) + " lc " + IntToString(lineColor)) # <<< Ugly strings
...
So does anyone know a good way to concatenate strings? Does mojo have f-strings yet?
3 Replies
toasty
toasty6mo ago
I made a naive/simple sprintf function if you want to give it a try. https://github.com/thatstoasty/gojo/blob/main/gojo/fmt/fmt.mojo You could also try an external_call to sprintf. It's been awhile, but I do recall the external call also working for me
fn sprintf[
*T: AnyType
](s: Pointer[c_char], format: Pointer[c_char], *args: *T) -> c_int:
"""Libc POSIX `sprintf` function
Reference: https://man7.org/linux/man-pages/man3/fprintf.3p.html
Fn signature: int sprintf(char *restrict s, const char *restrict format, ...).

Args: s: A pointer to a buffer to store the result.
format: A pointer to a C string containing the format.
args: The optional arguments.
Returns: The number of bytes written or -1 in case of failure.
"""
return external_call[
"sprintf", c_int, Pointer[c_char], Pointer[c_char] # FnName, RetType # Args
](s, format, args)
fn sprintf[
*T: AnyType
](s: Pointer[c_char], format: Pointer[c_char], *args: *T) -> c_int:
"""Libc POSIX `sprintf` function
Reference: https://man7.org/linux/man-pages/man3/fprintf.3p.html
Fn signature: int sprintf(char *restrict s, const char *restrict format, ...).

Args: s: A pointer to a buffer to store the result.
format: A pointer to a C string containing the format.
args: The optional arguments.
Returns: The number of bytes written or -1 in case of failure.
"""
return external_call[
"sprintf", c_int, Pointer[c_char], Pointer[c_char] # FnName, RetType # Args
](s, format, args)
Could also use a string builder, if you're constructing a large string. For smaller strings, maybe just sprintf or concat would be better. https://github.com/thatstoasty/gojo/blob/main/gojo/strings/builder.mojo
Hammad Ali
Hammad Ali6mo ago
So Mojo, doesn't have str.format and f-strings?
toasty
toasty6mo ago
Not at the moment
Want results from more Discord servers?
Add your server