출처 : http://www.freejava.wo.to/
(1) 알아두면 유용한 클래스
-String Class-
에궁 자바의 기초를 잡는다고 너무나 험난한 시간을 보내 왔습니다. 하지만 자바는 이제부터 시작입니다. 지금까지 배운 기초지식을 이용해서 어떤 식으로 자바를 이용할 수 있고 API를 통해서 새로운 클래스를 배우는 방법등에 대한 많은 것을 배울 것입니다. 그러니... 준비 단단히 하시기 바랍니다. ^^
그럼 이제부터 알아두면 언제든지 써먹을 수 있고 또한 자주 쓰이는 클래스들에 대해 차근차근 짚어보는 시간을 가져보도록 하겠습니다. 그럼 스타트.....!!!
String 클래스는 자료형에서 이미 보셨을 테지만(다 알지유.^^) 문자열을 표현하기 위해 자바에서 제공해주는 클래스입니다. 실질적으로 프로그램을 작성하다보면 char형 문자 '1'자나 int형 정수 보다는 String형 문자열을 가장 많이 사용하게 되고 또한 그에 따른 많은 기능들을 필요로 하게 됩니다. 그렇기 때문에 자바의 String 클래스는 이런 사용자들의 요구에 걸맞은 다양한 기능들을 포함하고 있습니다.하지만 대부분의 사람들이 자료형 클래스라는 이유로 대충 넘어가고 주의를 하지 않는 경우가 종종 있습니다만 String 클래스는 필요한 만큼 정말로 많은 기능이 있고 또한, 그 기능들을 잘 사용하면 문자열 표현의 많은 부분을 훨씬 편하게 할 수 있습니다. 그렇기 때문에 이런 String 클래스를 자유자재로 다루기 위해서 String 클래스를 API를 통해 직접 보면서 여러가지 메소드들의 기능과 사용법들에 대해 설명드리겠습니다. 우선, 클래스이니까 생성자를 통해 인스턴스를 생성해야지만 객체를 사용할 수 있습니다. String 클래스는 생각외로 많은 생성자를 가지고 있고 또한 각 생성자는 여러가지 인자에 따라 그에 맞는 String 객체를 생성하게 됩니다. 하지만 저희가 그것까지 전부다 볼 필요는 없습니다. (허나 아예 무시하고 잊어버리시면 안됩니다.--; 참고하십시요.) 왜냐하면 String 클래스는 자료형에도 쓰이기 때문에 String text = "야 이것은 테스트이다."; 라고 단순하게 문장을 써도 (여태껏 저희가 봐왔던 new를 이용한 인스턴스 생성및 객체 이용법 하고는 다르지만)String 클래스를 이용하실 수 있습니다. 그리고 지금으로서는 이것만으로 충분합니다. (분수 배우기...^^) 참, String 변수에 값을 입력하는것은 String 변수에 값을 입력하는 것이 아니라 그 값이 있는 주소를 입력시켜서 사용하는 거라는 것 기억하고 계시죠? (레퍼런스(reference) 라는것...기억해 두세요. ^^) 그럼 이제부터 실질적으로 String 클래스 API를 보면서 메소드에 대하여 한가지씩 알아 보겠습니다.
charAt public char charAt(int index) Returns the character at the specified index. An index ranges from 0 to length() - 1. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing. Parameters: index - the index of the character. Returns: the character at the specified index of this string. The first character is at index 0. Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string. |
charAt() 메소드는 int형 변수를 인자로 받아서 연산작업후 char형으로 결과를 리턴해주는 메소드입니다. 좀더 자세하게 설명하자면 charAt() 메소드는 인자로 받은 문자열의 int형 변수 index로 문자열의 index번째의 문자를 추출해서 반환해주는 행동을 해줍니다. 예를 들어 "Take It East." 라는 문자열이 있을 경우 charAt(3) 이라는 메소드는 char형으로 'e'라는 문자를 하나 반환하게 됩니다. (charAt() 메소드는 '0'부터 숫자가 시작되기 때문에 우리에게는 4번째 문자인 'e'가 반환되는 것입니다.)
length public int length() Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string. Returns: the length of the sequence of characters represented by this object. |
length() 메소드는 String형 문자열의 길이를 반환 합니다. 지금보신 length() 메소드는 java.lang.Object 클래스 안에 정의되어 있는 메소드로서 모든 클래스들이 반드시 상속 받기 때문에 거의 모든 클래스는 length()를 이용해서 길이를 구할수 있습니다. 예를 들어보면 String형 변수에 "testString" 라는 문자열이 들어가 있다고 생각하고 그 변수에 length() 메소드를 사용게 되면 우리는 쉽게 저장된 문자열의 길이 즉, 변수의 길이인 '8'을 리턴받을 수 있습니다.
indexOf public int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that: this.startsWith(str, k) is true. Parameters: str - any string. Returns: if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned. Throws: NullPointerException - if str is null. |
indexOf() 메소드는 String형 문자열 안에 특정문자가 있는지를 검사하는 메소드입니다. String 문자열 안에 포함된 문자를 검사해서 indexOf() 메소드로 받은 인자가 있는지 확인한후 있으면 그 문자가 처음으로 위치한 index를 리턴합니다. (그 문자가 마지막으로 위치한 인덱스를 리턴하기 위하여 lastIndexOf() 라는 메소드를 사용할 수도 있습니다.) 예를들어 "test String".indexOf('s'); 라는 구문이 있다면 문자열 안의 's'의 위치(index) 즉, '2' 라는 값(indexOf() 메소드도 문자열을 셀때 제일 처음은 0부터 시작합니다)이 int형 정수로 반환됩니다.
substring public String substring(int beginIndex,int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Examples: "hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile" Parameters: beginIndex - the beginning index, inclusive. endIndex - the ending index, exclusive. Returns: the specified substring. Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. |
substring() 메소드는 인자로 int형 index값을 두개 받아 연산후 그 결과로 String형 문자열을 반환하는 메소드입니다. int형 정수로 인자를 두개 받는데 하나는 시작점으로, 남은 하나는 끝날 기준으로 문자열의 index(순서)를 받아 그에 해당하는 문자열을 출력해줍니다. 쉽게 표현해 보면 substring(시작할 위치, 끝날위치)로 표현할 수도 있습니다.그리고 간단한 예를 들어 보면 "freeman Forever".substring(3,6)라고 구문이 주어질 경우 이 메소드는 String형 문자열인 "ema"을 반환하게 됩니다. (문자열의 인덱스 3의 위치에서 6의 위치 전 까지의 문자열)
concat public String concat(String str) Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. Examples: "cares".concat("s") returns "caress" "to".concat("get").concat("her") returns "together" Parameters: str - the String that is concatenated to the end of this String. Returns: a string that represents the concatenation of this object's characters followed by the string argument's characters. Throws: NullPointerException - if str is null. |
concat() 메소드는 String형 문자열의 뒤에 또다른 특정 String형 문자열을 붙일 수 있는 메소드입니다.우리가 흔히 출력할때 '+'를 이용하여 덧 붙여서 출력을 하는 방법과 거의 같은 기능을 하는 메소드로 만약, "test".concat("Print") 이라고 메소드를 사용하게 되면 이 구문은 리턴값으로 "testPrint"를 반환 하게 됩니다.
replace public String replace(char oldChar,char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar. Examples: "mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar" "the war of baronets".replace('r', 'y') returns "the way of bayonets" "sparring with a purple porpoise".replace('p', 't') returns "starring with a turtle tortoise" "JonL".replace('q', 'x') returns "JonL" (no change) Parameters: oldChar - the old character. newChar - the new character. Returns: a string derived from this string by replacing every occurrence of oldChar with newChar. |
replace() 메소드는 '바꿈을 당할 문자'와 '바꿔야 할 문자'를 인자로 받아서 String형 문자열 안에서 '바꿈을 당할 문자'를 찾아 '바꿔야 할 문자'로 교체하는 작업을 해주는 메소드입니다. 예를 들어 test라는 String변수에 "PowerFul java"라는 문자열이 들어가 있다고 치고 여기에 replace('w','e')라는 메소드를 사용하게되면 test라는 변수는 인자로 받은 문자를 교체한후 "Poeer java"라는 문자열을 반환하게 됩니다.
toLowerCase public String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale, which is returned by Locale.getDefault. If no character in the string has a different lowercase version, based on calling the toLowerCase method defined by Character, then the original string is returned. Otherwise, this method creates a new String object that represents a character sequence identical in length to the character sequence represented by this String object, with every character equal to the result of applying the method Character.toLowerCase to the corresponding character of this String object. Examples: "French Fries".toLowerCase() returns "french fries" Returns: the string, converted to lowercase. See Also: Character.toLowerCase(char), toUpperCase() |
toLowerCase() 메소드는 딱 보면 아시겠지만 String형 문자열을 모두 소문자로 대치시켜주는 메소드입니다. 예를 들어 "telMMMME".toLowerCase() 라는 구문은 대문자만이 모두 소문자로 대치되어 "telmmmme"를 반환하게 됩니다. 이것과 비슷하며 대칭되는 메소드가 하나 있는데 toUpperCase()라는 메소드입니다. 이 메소드는 toLowerCase()랑 정반대 되는 메소드로서 toLowerCase()가 대문자를 소문자로 바꿔주는 기능을 하는 대신에 toUpperCase()는 소문자를 대문자로 바꿔주는 기능을 합니다. 사용방법은 toLowerCase()와 똑같습니다. 보통 이와 같은 메소드는 키보드 입력을 받을때 대,소문자 상관없이 받은후 이벤트를 발생할 경우에 많이 사용됩니다. (왜 그런지는 추측해 보시면 아실수 있으실 겁니다.^^)
trim public String trim() Removes white space from both ends of this string. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned. Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned. Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1). This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well. Returns: this string, with white space removed from the front and end. |
지금 보신 trim() 메소드는 문자 앞,뒤의 필요없는 여백을 제거해 주는 기능을 가지고 있는 메소드입니다.양쪽 여백을 제거해주기 때문에 불필요한 데이터를 제거하거나 String 문자열만을 추출할때 많이 사용됩니다. 예를 들어 "kim kimki " 라는 문장은 데이터 베이스나 하드등의 자료에 저장될때 10바이트가 소모됩니다.(1바이트 = 1글자) 왜냐하면 여백도 문자 하나처럼(1바이트) 인식하기 때문입니다. 그렇지만 사실 여백은 우리가 필요로 하는 자료는 아닙니다. 이럴경우 trim() 메소드를 사용하면 자동으로 문자열의 여백을 제거해 주고 우리가 원하는 문자열만 리턴해주게 됩니다. 에궁 힘드셨습니다. 여기까지가 String 클래스에서 기본적으로 자주 사용되는 메소드의 목록과 사용법에 관한 것들 입니다. 메소드의 기능들을 확인해 보셨으니까 어떤 식으로 이용하면 프로그램을 짜야할때 편하게 이용할지 다 생각이 있으리라고 믿습니다.^^ String 클래스는 은근히 자주 쓰이면서 잊어먹기 쉬운 클래스이니 꼭 기억하시길 바라겠고 마지막으로 모든 메소드의 기능을 확인하는 간단한 소스를 작성할테니 실행해보시고 메소드의 기능들을 확실하게 익히시기 바라겠습니다.
public class StringTest { public static void main(String[] args){ String free = "Freeman's Javajaby"; System.out.println(free.charAt(4)); System.out.println(free.length()); System.out.println(free.indexOf("e")); System.out.println(free.substring(3,12)); System.out.println(free.concat(" da")); System.out.println(free.replace('e', 't')); System.out.println(free.toLowerCase()); System.out.println(free.toUpperCase()); System.out.println(free.trim()); } } |
결과 : m 18 2 eman's Ja Freeman's Javajaby da Frttman's Javajaby freeman's javajaby FREEMAN'S JAVAJABY Freeman's Javajaby |


::: 사람과 사람의 교감! 人터넷의 첫 시작! 댓글을 달아주세요! :::