Hey folks, I am gonna translate a code snippet from cpp to rust, but I occur some problems about iterator, here is the code:
string removeComments(string prgm)
{
int n = prgm.length();
string res;
// Flags to indicate that single line and multpile line comments
// have started or not.
bool s_cmt = false;
bool m_cmt = false;
// Traverse the given program
for (int i=0; i<n; i++)
{
// If single line comment flag is on, then check for end of it
if (s_cmt == true && prgm[i] == '\n')
s_cmt = false;
// If multiple line comment is on, then check for end of it
else if (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/')
m_cmt = false, i++;
// If this character is in a comment, ignore it
else if (s_cmt || m_cmt)
continue;
// Check for beginning of comments and set the approproate flags
else if (prgm[i] == '/' && prgm[i+1] == '/')
s_cmt = true, i++;
else if (prgm[i] == '/' && prgm[i+1] == '*')
m_cmt = true, i++;
// If current character is a non-comment character, append it to res
else res += prgm[i];
}
return res;
}
And this is my rust code:
pub fn clear_comment() {
let mut single_comment = false;
let mut multi_comment = false;
let mut stdin = io::stdin();
let mut buffer: Vec<u8> = vec![];
match stdin.read_to_end(&mut buffer) {
Ok(bytes) => {
let input = String::from_utf8(buffer).unwrap();
let chars = input.chars().peekable();
for char in chars {
if (single_comment && char == '\n') {
single_comment = false;
} else if (multi_comment && char == '*' && chars.peek().unwrap() == &'/') {
multi_comment = false;
} else if (char == '/' && chars.peek().unwrap() == &'/') {
single_comment = true;
// chars.next();
}
}
}
Err(error) => println!("Error:{}", error),
}
}
I don't know how to handle prom[i]
and progm[i+1]
in Rust, I have tried peek()
, but it seeems I did somethings wrong
Any suggestion will be appreciated