The awkwardness of strings in Rust

I'm still really new to programming in Rust and I'm currently writing a small tool in Rust where at least half of the purpose of writing it is to get better at Rust (If I wanted to get it done quickly, I would be better off using some language I'm more familiar with).

Anyway, I'm attempting to extract some data from a textual config file.
While doing so I have found the String type really awkward to work with.

For example, the config file contains strings enclosed in double quotes. The quotes can also be escaped as \", so I also need to know the char immediately before the quote character.
If I use .find() on the string, then I get a byte position (good for slicing) but I can't go back to the previous char because I don't know how many bytes it is made of.
If I step through the string by iterating with .chars(), then there appears to be no way to get the byte position out of the iterator. Of course I can count the number of iterations to get the number of chars, but with utf-8 that's not really useful. In particular, I would want the byte position in order to be able to make string slices when I extract the input into individual variables.

I was hoping there would be methods like string_iterator.get_byte_position() or maybe mystring.split_at(string_iterator) or something like that. I did not find anything like that.

It seems other people are turning strings into Vec<char> when they want to actually look at the content of the string.
Is this the recommended way to work with strings? It seems like an epic fail for the String type if it's not suitable for anything other than displaying strings.

Am I missing something here?

.char_indices() is your friend, with a handy convenience method attached to it: .as_str() :wink:

Also, the .peekable() (Iterator) adaptor lets you look at the next element of an iterator without necessarily consuming it. Combining both you can get quite far when trying to handle escape chars :slightly_smiling_face:

Ah, char_indices is exactly what I was looking for.
Thanks!

1 Like