JAVA2009. 11. 24. 22:17

String, StringBuilder, StringTokenizer 클래스의 메소드 사용 예제 Java

2009/01/21 19:02

작성자: 베레(lsj403)

/*
//String클래스 length, charAt 메소드 사용예제
class StringExample1 {
 public static void main(String[] args) {
  String str = "자바 커피";
  int len = str.length();  //length() [int / Returns the length of this string.]
  for(int cnt = 0; cnt<len; cnt++) {
   char ch = str.charAt(cnt); //charAt(int index) [char / Returns the char value at the specified index.]
   System.out.println(ch);
  }
 }
}//class 결과 : 자바 커피
*/


//동등 연산자를 이용한문자열 비교 프로그램
/* //리터럴을 이용한 객체 생성
class StringExample2 {
 public static void main(String[] args) {
  String str1 = "자바"; //리터럴 문자를 선언
  String str2 = "자바"; //리터럴 문자를 선언
  if(str1==str2) //리터럴로 선언된 문자열의 경우 S.S(문자열저장소)에서 객체 참조
   System.out.println("같음");
  else
   System.out.println("다름");
 }//main
}//class 결과 : 같음
*/
//생성자를 이용한 객체 생성
/*
class StringExample3 {
 public static void main(String[] args){
  String str1 = new String("자바"); //생성자로 문자를 선언
  String str2 = new String("자바"); //생성자로 문자를 선언
  if(str1 == str2)  //다른 생성자로서 다른 문자열에 생성  (객체 3개= 자바, str1, str2 객체가 생성
   System.out.println("같음");
  else
   System.out.println("다름");
 }//main
}//class 결과 : 다름
*/

/*
//str1.equals(str2)
//String의 equals 는 내용비교
//Object의 equals 는 True or False로 확인

class StringExample4 {
 public static void main(String[] args) {
  String str1 = "자바"; //리터럴로 자바 생성
  String str2 = "자바"; //리터럴로 자바 생성
  if(str1.equals(str2)) //equals 는 같은 문자열의 내용인지 내용 비교 후 True or false 반환
   System.out.println("같음");
  else
   System.out.println("다름");
 }//main;
}//class 결과 : 같음
*/

/*
//str1.equals(str2)
//String의 equals 는 내용비교
//Object의 equals 는 True or False로 확인
class StringExample5 {
 public static void main(String[] args) {
  String str1 = new String("자바"); // 문자열 객체 생성
  String str2 = new String("자바"); //문자열 객체 생성
  if(str1.equals(str2)) //equals 는 같은 문자열의 내용인지 내용 비교 후 True or false 반환
   System.out.println("같음");
  else
   System.out.println("다름");
 }//main
}//class 결과 : 같음
*/

/*
//String 클래스의 substring 메소드 사용
class StringExample6 {
 public static void main(String[] args) {
  String str = "뇌를 자극하는 자바";
  System.out.println(str.substring(3));   // [string / substring(int beginIndex)  Returns a new string that is a substring of this string.]
  System.out.println(str.substring(3,7)); // [string / substring(int beginIndex, int endIndex)  Returns a new string that is a substring of this string.]
 }//main  결과 : 자극하는 자바 (뇌를 )제외한 나머지를 반환
}//class  결과 : 자극하는      (뇌를 )시작부터 3번째까지, 시작부터 7번째까지 사이의 문자열을 반환
*/

/*
//string 문자열 조작 메소드
class StringExample2 {
 public static void main(String[] args) {
  String str1 = "     Let it be.     "; //공백을 포함한 문자 리터럴 선언
  String str2 = str1.trim();  // 공백 제거 메소드 [String / trim() Returns a copy of the string, with leading and trailing whitespace omitted.]

  System.out.println(str2); // Let it be. // str1 변수값의 참조값을 trim 후 출력
  System.out.println(str2.concat("Speaking words of wisdom."));  //Let it be Speaking words of wisdom.
  //문자열 접합 연산자 [String / concat(String str) Concatenates the specified string to the end of this string.]
  System.out.println(str2.toUpperCase()); //LET IT BE.
  //문자열을 대문자로 변환 [string / toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.]
  System.out.println(str2.toLowerCase()); //let it be
  //문자열을 소문자로 변환 [string / toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.]
  System.out.println(str2.replace('e','a')); //lat it ba.
  //문자열을 다른 문자열로 변환 [string / replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.]
  System.out.println(str1); // Let it be.
  System.out.println(str2); //Let it be
 }//main
}//class
*/


//StringBuilder 클래스 생성자
//파라미터 없는 객체 생성시 +16인 버퍼 생성, 파라미터에 버퍼 값을 넣을수 있음.
/*
class StringBuilderExample1 {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("역사를 하노라고 맨땅을 파다가 ");
  System.out.println(sb);
  System.out.println(sb.append("커다란 고인돌을 끄집어 내어놓고 보니"));
  //문자열뒤에 문자열을 붙임 [stringbuilder / append(String str) Appends the specified string to this character sequence.]
  System.out.println(sb.insert(26, "하나"));
  //offset 위치에 문자열 삽입. [StringBuilder / insert(int offset, char c) Inserts the string representation of the char argument into this sequence.]
  System.out.println(sb.delete(21, 23));
  //시작점과 종점사이를 삭제 [StringBuilder / delete(int start, int end) Removes the characters in a substring of this sequence.]
  System.out.println(sb.deleteCharAt(9));
  //인덱스의 위치를 삭제 [StringBuilder  /  deleteCharAt(int index) Removes the char at the specified position in this sequence.]
 }
}//class
*/
/*
//capacity(); 버퍼크기를 리턴하는 메소드
class StringBuilderExample2 {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("푸른 산빛을");
        //sb.ensureCapcity(50); //미리 버퍼 공간을 할당.
  printStringBuilder(sb);
  sb.append("깨치고 적은 길을 걸어서 참어 떨치고 갔습니다.");
  printStringBuilder(sb);
  sb.insert(10, "단풍
  나무 숲을 향하여 난");
  printStringBuilder(sb);
 }//main
 static void printStringBuilder(StringBuilder sb) {
  String str = sb.toString(); //버퍼의 문자열을 string객체로 만들어서 리턴하는 메소드
  //[string / toString() Returns a string representing the data in this sequence.]
  int len = sb.length(); //문자열의 길이를 int로 반환메소드
  //[int / length() Returns the length (character count). ]
  int bufSize = sb.capacity(); //문자열의 크기를 반환하는 메소드
  //[int / capacity()  Returns the current capacity.]
  System.out.printf("%s(%d):: %d %n ", str, len, bufSize);
 }
  }//class
  */

//[void / ensureCapacity(int minimumCapacity) Ensures that the capacity is at least equal to the specified minimum.  ensureCapacity(100);
//버퍼의 크기를 미리 증가 시키는 메소드

/*
//trimToSize() //버퍼 크기를 문자열의 크기에 맞게 맞춤. 불필요한 버퍼는 제거
class StringBuilderExample4 {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder(50);
  sb.append("자바");
  System.out.println(sb + ": " + sb.capacity());
  sb.trimToSize();
  // [void / trimToSize()   Attempts to reduce storage used for the character sequence. ]
    System.out.println(sb + ": " + sb.capacity());
 }//main
}//class
*/

/*
//StringTokenizer를 이용한문자열 분리
import java.util.StringTokenizer;
//StringTokenizer : 문자열 분리 클래스
class StringTokenizerExample1 {
 public static void main(String[] args) {
  StringTokenizer stok = new StringTokenizer("사과 복숭아 배");
  while(stok.hasMoreTokens()) {
   //토큰을 가질경우 true, 없을시 false [boolean / hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.]
   String str = stok.nextToken();
   //다음 토큰이 있는지 찾아서 저장 [string / nextToken() Returns the next token from this string tokenizer.]
   System.out.println(str);
  }
 }//main
}//class
*/

/*
import java.util.StringTokenizer;
//StringTokenizer : 문자열 분리 클래스
class StringTokenizerExample1 {
 public static void main(String[] args) {
  StringTokenizer stok = new StringTokenizer("사과,복숭아,배", ","); //구분자 Delim
  while(stok.hasMoreTokens()) {
   //토큰을 가질경우 true, 없을시 false [boolean / hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.]
   String str = stok.nextToken();
   //다음 토큰이 있는지 찾아서 저장 [string / nextToken() Returns the next token from this string tokenizer.]
   System.out.println(str);
  }
 }//main
}//class
*/

/*
import java.util.StringTokenizer;
//StringTokenizer : 문자열 분리 클래스
class StringTokenizerExample1 {
 public static void main(String[] args) {
  StringTokenizer stok = new StringTokenizer("사과=10|복숭아=20|배=30", "=|", true); //true 사용시 구분자까지 구획문자도 포함
  while(stok.hasMoreTokens()) {
   //토큰을 가질경우 true, 없을시 false [boolean / hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.]
   String token = stok.nextToken();
   //다음 토큰이 있는지 찾아서 저장 [string / nextToken() Returns the next token from this string tokenizer.]
   if(token.equals("=")
    System.out.println("\t");
   else if(token.equlas("|"))
    System.out.println("\n");
   else
    System.out.println(token);
  }
 }//main
}//class
*/

Posted by Tiwaz