Difficulty: Easy · Puzzle 2 of 6 · Topic: String and Casting Puzzles
After one character replacement, what are final string, length, and ASCII code?
module p2;
string s = "dv puzzle";
int ch;
initial begin
s.putc(3, 8'h5f); // '_'
ch = s.getc(4);
$display("s=%s len=%0d ch=%0d", s, s.len(), ch);
end
endmoduleString indexing is zero-based and `putc` writes at an index, it does not insert and shift.
1) Original index 3 is character `p` in `"dv puzzle"`.
2) `putc(3,'_')` replaces `p`, giving `"dv _uzzle"`.
3) Length remains 9 because replacement is in-place.
4) Index 4 is `u`, whose ASCII code is 117.Answer: s=dv _uzzle, len=9, ch=117
Checked by running the code in Verilator 5; the printed output supports the answer above. putc replaces in place so the length stays 9; Icarus 13 has no putc or getc.
`putc` overwrites in place (length stays 9) and string indexing starts at 0, so index 3 is the `p`, not the space.
What does `s.getc(100)` return for out-of-range index? Model answer: 0 (run), and the string is not changed.
I would count from 0, because string indexing starts at zero. Index 3 is the p, putc replaces it in place with an underscore, so the string is dv underscore uzzle and the length stays 9. Index 4 is u, whose code is 117. The trap is counting from 1 or thinking putc inserts. I would check the index range, since a call outside it does nothing.