String indexing etc

Hi! I'm very new to Rust (it's awesome btw).

I'm looking for the most appropriate method 'lex' a string. How should I go about iterating through the characters in a string (and which 'string' should I use?).

Many thanks

How should I go about iterating through the characters in a string

Use the chars() method to iterate over the characters in a string. Like this:

for ch in string.chars() {
    // Do something with ch
}

and which 'string' should I use?

That depends on exactly how you structure your code. If this object owns the string, you want to use String. If it's just borrowing the string from someone else, it should use an &str.

1 Like

I just want to point out that char_indices is also a great method for iterating over chars. The nice part is that it also allows you to keep track of where in the string you are, by returning the byte position. This is nice if you, for example, want to take a slice from one index to another after stepping through its characters.

Oh, and while I'm here; tendril is a nice crate for chopping up strings and vectors without having to copy them.

2 Likes

Thanks a lot!