Efficient way to index and iter over *const char or CStr

I have a case of needing to do the following 2 things

  1. To iterate over characters in *const char which is a null terminated string and check if a character exists. I want to do something like
file: *const libc::c_char;
   if ( file.iter().any(|i| i=='/'))  {
    do something.
  1. Do indexing. Check if the char at const c_char or some index into that pointer is '\0'. I am doing the following, is this the most efficient?
file: *const libc::c_char
((*file.offset(0)) as char) ==  '\0'
  1. Also is there a way to index into CStr object?
  2. Also is there a way to iterarate over CStr object?

There's https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.to_bytes that allows you to iterate and index it like a slice.

The most efficient manner would be:

cstr.to_bytes().iter().position(|c| c == b'C')

It takes a closure as filter and returns and Option<usize> where that usize is an index in the CStr if the return is none then the character(or u8 in this case) is not present.
Now, if you want to support UTF-8 you will need first convert your CStr to a &str or String, you can achieve that with the to_str method or with to_string_lossy then you can apply the above of this manner:

my_string.chars().position(|c| c == '🔍')

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.