// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/12/String.jack /** * Represents character strings. In addition for constructing and disposing * strings, the class features methods for getting and setting individual * characters of the string, for erasing the string's last character, * for appending a character to the string's end, and more typical * string-oriented operations. */ class String { field Array buffer; field int length; field int maxLen; /** constructs a new empty string with a maximum length of maxLength * and initial length of 0. */ constructor String new(int maxLength) { if (maxLength = 0) { let maxLength = 1; // min length 1 for alloc safety? } if (maxLength > 0) { let buffer = Array.new(maxLength); } let maxLen = maxLength; let length = 0; return this; } /** Disposes this string. */ method void dispose() { if (maxLen > 0) { do buffer.dispose(); } do Memory.deAlloc(this); return; } /** Returns the current length of this string. */ method int length() { return length; } /** Returns the character at the j-th location of this string. */ method char charAt(int j) { return buffer[j]; } /** Sets the character at the j-th location of this string to c. */ method void setCharAt(int j, char c) { let buffer[j] = c; return; } /** Appends c to this string's end and returns this string. */ method String appendChar(char c) { if (length < maxLen) { let buffer[length] = c; let length = length + 1; } return this; } /** Erases the last character from this string. */ method void eraseLastChar() { if (length > 0) { let length = length - 1; } return; } /** Returns the integer value of this string, * until a non-digit character is detected. */ method int intValue() { var int val, i, d; var boolean neg; let val = 0; let i = 0; let neg = false; if (length > 0) { if (buffer[0] = 45) { // '-' let neg = true; let i = 1; } } while (i < length) { let d = buffer[i] - 48; // '0' is 48 if ((d > -1) & (d < 10)) { let val = (val * 10) + d; let i = i + 1; } else { let i = length; // break } } if (neg) { return -val; } return val; } /** Sets this string to hold a representation of the given value. */ method void setInt(int val) { let length = 0; // Clear string if (val < 0) { let val = -val; do appendChar(45); // '-' } do int2String(val); return; } // Helper for recursive int printing method void int2String(int val) { var int lastDigit; var int c; let lastDigit = val - ((val / 10) * 10); // val % 10 let c = lastDigit + 48; if (val < 10) { do appendChar(c); } else { do int2String(val / 10); do appendChar(c); } return; } /** Returns the new line character. */ function char newLine() { return 128; } /** Returns the backspace character. */ function char backSpace() { return 129; } /** Returns the double quote (") character. */ function char doubleQuote() { return 34; } }