Is there any StringBuilder like utility in stdlib, or should I build one?

I am using stdlib_string_type and stdlib_stringlist_type a lot in my codebase.

I wrote a kind of preprocessor in fortran, to write more fortan! But it’s pretty slow and the core of the project is to append strings with strings, and then stringlists with stringlists. At the end, everything is dump into a file. It is not optimal at all and takes several hundred of milliseconds to run.

I was thinking that a nice StringBuilder extension should have it’s place in the stdlib. I didn’t find anything that looks like it. Here is what I have in mind: StringBuilder in C# and the source code stringbuilder.cs.

The future stdlib_string_builder should contain a mutable array of stdlib_string_type. The private array can grow from power of 2 to power of 2. It will be able to append new strings fast, and has a to_string method that returns every strings concatenate in one go.

So, what do you think of this idea? Is it feasible? Is there something already existing that I didn’t find?

1 Like

Yes I think this is a good idea, but I don’t know if a separate “builder” really is needed.

I experimented once with implementing a mutable string type in Fortran inspired by Rust’s String which will grow only when needed instead of re-allocating on each assignment (aka. immutable strings). I found it worked very nicely, but I never got around to publish it as something useful, but I just uploaded it as a GitHub Gist if you want some inspiration: Mutable Fortran string type · GitHub The current implementation grows when needed, but cannot shrink to fit its content which also would be natural to implement.

1 Like

Making a separate builder is the way it has been done in C#, I guess for separating the mutable one from the immutable one, which make sense? I don’t think changing the current stdlib_string_type to make it mutable is a good idea :sweat_smile:

I haven’t seen anything published separately, but you might want to look at how I did something similar in rojff here.

@cyrilgandon ,

If you have a need for it and which is indeed the case as you explain, then it definitely is a good idea.
Now I am not aware of anything that is exactly analogous to C# StringBuilder but hopefully you will find something that works well.

If not, I think it is definitely feasible in Fortran and you can attempt it. There are no added limitations beyond what you have already seen with the 2 types in stdlib.