Fix string index out of range exception