Is this the most idiomatic way to filter text?

I'm trying to filter lines from the start of some text which start with the character 'z' before processing it in a method chain which I'd like to preserve.

    text //: String
    .skip_while(|line| line.starts_with('z'))

Is there a better way of doing this?

what do you mean by "in a method chain"? it's not very clean to me from the context.

being "idiomatic" is not all about coding styles, to me, writing "idiomatic" code means writing correct and efficient code for a particular problem.

as for the code, depending on you use case, it might not be optimal, you need state your goal more clearly, e.g. at least what is the type signature of long_method_chain(), what is your expectation, etc.

but for the code snippet, immediately I have some questions:

why "split_inclusive('\n')"; is "lines()" not usable in your situation?

what is the behavior of "long_method_chain()"? does it process the text line by line? does it consumes an owned input String? or does it only borrows a &str?

depending on the actual usage, you might use different strategies to achive better performance, e.g: you might be able avoid unnecessary allocation caused by collecting into a temporary String; or you might avoid search (and split) the entire string if the prefix you want to strip is relative small portion.

1 Like

Sorry I wasn't clear, basically what I want is to have the rest of the (multiline) text unchanged, except for the first few lines that start with 'z'.
It's a weird format where data can span across lines so I can't process them individually, which is why I'm using split_inclusive('\n') and joining them after.
Also yeah, I'd like to not allocate a new String since the method chain takes a &str.

So my question is, is there a way to do this more elegantly without allocating a new String with it still being in a functional form.

Here's one way.


Nice, thanks!
I didn't think of counting and slicing.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.