'자바를자바답게하는클래스[String클래스]'에 해당되는 글 1건

  1. 2008.08.14 자바를자바답게하는클래스[String클래스]
2008. 8. 14. 17:44

자바를자바답게하는클래스[String클래스]

java.lang.String

String 클래스는 문자열을 표현하는 클래스이다. 문자열은 문자(char)들의 배열로 볼 수 있다. String 클래스는 문자열을 char형 배열에 저장하여 관리한다.



String 클래스의 유용한 생성자

public String(String original)  -  original의 문자열과 같은 문자열을 가진 객체를 만든다.


public String(char value[])  -  char 배열 value를 문자열로 하는 객체를 만든다.

 

public String(char value[], int offset, int count)  -   char형 배열 value의 원소 중, offset(시작원소번호)부터 count(개수)개의 문자들을 문자열로 가진다.

 

public String(StringBuffer buffer)  -  StringBuffer형 객체 buffer와 같은 문자열을 가진다.

 

위에서 생략된 생성자에 대하여 알고싶다면 API 문서를 참고하면 된다. StringBuffer 클래스는 조금 후에 알아볼 것이다.

 

##String1.java##

 

public class String1{

  public static void main(String[] args){

    String s1=new String("abc");

    String s2=new String(s1);                             // s1과 같은 문자열

   

    char[] value=new char[]{'A','B','C','D','E','F','G','H'};

    String s3=new String(value);                         // 배열 전체를 복사

    String s4=new String(value,3,4);    // 'D'부터 'G'까지의 문자들을 문자열로 함

   

    System.out.println(s1);

    System.out.println(s2);

    System.out.println(s3);

    System.out.println(s4);

  }

}

 

##출력 결과##

abc

abc

ABCDEFGH

DEFG

 

 

String 클래스의 유용한 메소드 1

 

public char charAt(int index)

문자열의 문자 중, index 위치에 있는 문자를 반환한다. index는 0부터 시작한다.

 

public int compareTo(String anotherString)

anotherString의 문자열과 this의 문자열을 비교해서 this가 크면 양 수(+)를, 작으면 음수(-)를, 같으면 0을 반환한다.

 문자열 대소비교: "abc" < "bbc", "abc" > "ABC", "abc" = "abc"

 

public int compareToIgnoreCase(String anotherString)

대소문자를 구분하지 않고 비교한다(compareTo 메소드).

 

public String concat(String str)

문자열 뒤에 str를 추가하여 String 객체를 반환한다.

 

public boolean endsWith(String suffix)

this의 문자열이 문자열 suffix로 끝나면 true, 아니면 false를 반환한다.

 

public boolean equals(Object anObject)

anObject와 this가 같은 문자열을 가지면 true를 반환한다.

 

public boolean equalsIgnoreCase(String anotherString)

대소문자를 구분하지 않고 비교해서 같으면 true를, 아니면 false를 반환한다.

 

##String2.java##

 

public class String2{

  public static void main(String[] args){

    String s1=new String("ABCDEFGH");

    System.out.println(s1.charAt(4));                               // E

    System.out.println(s1.compareTo("abc"));                      // -32

    System.out.println(s1.compareToIgnoreCase("abcdefgh"));     // 0

    System.out.println(s1.concat("abc"));                     // ABCDEFGHabc

    System.out.println(s1.endsWith("FGH"));                       // true

    System.out.println(s1.equals("ABCDEFGH"));                  // true

    System.out.println(s1.equalsIgnoreCase("abcdefgh"));        // true

  }

} 

 

String 클래스의 유용한 메소드 2

public int indexOf(int ch)

this의 문자열을 앞에서부터 검색하여 문자 ch가 처음으로 나타난 위치를 반환한다. 위치(index)는 0부터 시작한다.

public int indexOf(int ch, int fromIndex)

this의 문자열을 fromIndex부터 검색하여 문자 ch가 처음으로 나타난 위치를 반환한다.

public int indexOf(String str)

this의 문자열을 앞에서부터 검색하여 문자열 str이 처음으로 나타난 위치를 반환한다.

public int indexOf(String str, int fromIndex)

this의 문자열을 fromIndex부터 검색하여 문자열 str이 처음으로 나타난 위치를 반환한다.

public int lastIndexOf(int ch)

public int lastIndexOf(int ch, int fromIndex)

public int lastIndexOf(String str)

public int lastIndexOf(String str, int fromIndex)

 this의 문자열을 뒤에서 검색하여 문자(ch) 또는 문자열(str)이 처음으로 나타난 위치를 반환한다.

##String3.java##

public class String3{

  public static void main(String[] args){

    String s1=new String("This is a String");

    System.out.println(s1.indexOf('i'));           // 2

    System.out.println(s1.indexOf('i',7));         // 13

    System.out.println(s1.indexOf("is"));         // 2

    System.out.println(s1.indexOf("is", 5));      // 5

    System.out.println(s1.lastIndexOf("is"));     // 5

  }

} 

 

String 클래스의 유용한 메소드 3

 

public int length()

문자열의 길이(문자의 개수)를 반환한다.

 

public String replace(char oldChar, char newChar)

문자열의 문자들 중에서 oldChar를 newChar로 바꾸어서 반환한다.

 

public String replaceAll(String regex, String replacement)

문자열에서 regex 문자열을 replacement 문자열로 바꾸어서 반환한다.

 

public boolean startsWith(String prefix)

문자열이 preffix로 시작하면 true를, 아니면 false를 반환한다.

 

public String substring(int beginIndex)

beginIndex부터 끝까지의 문자열을 반환한다.

 

public String substring(int beginIndex, int endIndex)

beginIndex부터 endIndex 까지의 문자열을 반환한다.

 

 

##String4.java##

  

public class String4{

  public static void main(String[] args){

    String s1=new String("This is a String");

    System.out.println(s1.length());                // 16

    System.out.println(s1.replace('i','Q'));         // ThQs Qs a StrQng

    System.out.println(s1.replaceAll("is","IS"));    // ThIS IS a String

    System.out.println(s1.startsWith("This"));      // true

    System.out.println(s1.substring(5));           // is a String

    System.out.println(s1.substring(5,13));        // is a Str

  }

}

 

String 클래스의 유용한 메소드 4

 

public String toLowerCase()

소문자로 변환된 문자열을 반환한다.

 

public String toUpperCase()

대문자로 변환된 문자열을 반환한다.

 

public String trim()

문자열 앞뒤 공백을 제외한 문자열을 반환한다.

 

public static String valueOf(Object obj)

valueOf(boolean b), valueOf(char c), valueOf(int I), valueOf(long l)

valueOf(float f), valueOf(double d)

 각각의 자료형을 문자열로 변환하여 반환한다.

 

 

##String5.java##


public class String5{

  public static void main(String[] args){

    String s1=new String("This is a String");

    System.out.println(s1.toLowerCase());             // this is a string

    System.out.println(s1.toUpperCase());             // THIS IS A STRING

    System.out.println(new String("  abc  ").trim());   // abc

    System.out.println(String.valueOf(1234));          // "1234"

    System.out.println(String.valueOf(12.345));        // "12.345"

  }

}


 

String 클래스는 많은 메소드를 제공하지만, 정작 자신의 문자열에 문자를 추가하거나 삭제하지 못한다.

 

 

String s1=new String("abc");

String s2=s1.concat("def");  // s1의 문자열은 바뀌지 않는다.

System.out.println(s1);      // abc

System.out.println(s2);      // abcdef