C++로 Java의 String 클래스 구현하기 * 주의 : 매우 구림 * String.h 헤더파일 {{{ class String { private: char* values; char* valuesForCase; int length; int offset; int lengthForSubs; public: String(); String(const char* origin); String(const String str, const int offset, const int length); ~String(); public: const char charAt(const int offset); void concat(const char* str); bool equals(String str); bool equals(const char* str); bool isEmpty(); const char* toLower(); const char* toUpper(); void print(); }; }}} * String.cpp 소스파일 {{{ {{{#include #include #include #include "String.h" String::String() { values = NULL; valuesForCase = NULL; offset = -1; length = 0; } String::String(const char* origin) { int i; for(i=0; ; i++) { if(origin[i] == '\0') break; } offset = 0; length = i; values = (char*)malloc(sizeof(char) * length); valuesForCase = NULL; for(i=0 ; ioffset = 0; this->length = length; values = (char*)malloc(sizeof(char) * length); valuesForCase = NULL; int i; for(i=0; ilength+i; char* newValues = (char*)malloc(sizeof(char) * newLength); for(i=0; ilength) newValues[i] = values[i]; else if(i >= this->length) newValues[i] = str[i-this->length]; } String temp(newValues); temp.length = newLength; return temp; } bool String::equals(String str) { if(this->length != str.length) return false; for(int i=0; ilength; i++) { if(values[i] != str.values[i]) return false; } return true; } bool String::equals(const char* str) { int i; for(i=0; ; i++) { if(str[i] == '\0') break; } if(i != length) return false; for(i=0; ilength; i++) { if(values[i] != str[i]) return false; } return true; } const char* String::toLower() { if(valuesForCase != NULL) free(valuesForCase); valuesForCase = (char*)malloc(sizeof(char) * (length+1)); int i; for(i=0; i= 65 && values[i] <= 90) { valuesForCase[i] = values[i]+32; } } valuesForCase[i] = '\0'; return valuesForCase; } const char* String::toUpper() { if(valuesForCase != NULL) free(valuesForCase); valuesForCase = (char*)malloc(sizeof(char) * (length+1)); int i; for(i=0; i= 90 && values[i] <= 122) { valuesForCase[i] = values[i]-32; } } valuesForCase[i] = '\0'; return valuesForCase; } void String::print() { for(int i=0; i #include "String.h" int main() { String str("dddd"); // charAt if(str.charAt(3) == 'd') // OK printf("oo \n"); // concat String strCon = str.concat("ccc"); // equals String str2("ddddccc"); if(str2.equals(strCon)) // OK printf("oo2 \n"); // toUpper String temp(str2.toUpper()); if(temp.equals("DDDDCCC")) printf("DDDDCCCC is same\n"); // toLower String temp2(temp.toLower()); if(temp2.equals("ddddccc")); printf("ddddccc is same\n"); // isEmpty if(!str2.isEmpty()) printf("str2 is not empty\n"); String str3; if(str3.isEmpty()) printf("str2 is empty\n"); return 0; } }}} ---- * 짱재밌당!! 올해 데블스에도 이런거하자 - [서지혜]