본문 바로가기

Java dev/Java Basic

String 클래스의 주요 메소드들

String 클래스의 주요 메소드들


int length();

char charAt(int i);

byte[] getByte();

boolean equals(Object str);

boolean equalsIgnoreCase(String str);

boolean startsWith(String str);

boolean endsWith(String str);

int compareTo(String str);

int indexOf(char ch); (String str); (int ch, int startIndex); (String str, int startIndex);

int lastindexOf(char ch); (String str); (int ch, int startIndex); (String str, int startIndex);

String substring(int startIndex); (int startIndex, int endIndex);

String concat(String str);

String replace (char original, char replacement);

String toLowerCase();

String toUpperCase();

String trim();

Static String valueOf(double num); (long num); (Object obj); (char chars[]); (char chars[], int startIndex, int numChars);



String substring(int startIndex); (int startIndex, int endIndex);


메소드 이름은 같지만 매개 변수의 수나 데이터형이 다른 경우를 오버로딩(overloding)이라고 한다.

<%
// 문자열 변수를 선언하고 초기화한다.
String sa = "This is a test string.";
String sb;
char buf[]=new char[20];
%>
<HTML>
<HEAD>
<TITLE> String Class(1) </TITLE>
</HEAD>
<BODY>
[문자열 길이] <BR>
<%= sa.length() %> <BR>
<BR>
[문자및 문자열 추출(extraction)]<BR>
3 번째 문자 : <%= sa.charAt(3) %> <BR>
10-14 번째 문자열 :
<%
sb = sa.substring(10, 14);
out.println(sb);
%>
<BR> <BR>
[문자열 비교]<BR>
<%
// 대소문자를 구별하여 비교한다.
if ( sb.equals("Test") )
    out.println(" 객체 sb 의 값은 Test 이다. <BR>");
// 대소문자를 구별하지 않고 비교한다.
if ( sb.equalsIgnoreCase("Test") )
    out.println(" 객체 sb 의 값은 Test 이다. <BR>");
%>
</BODY>
</HTML>



<%
int i, rv;
// 문자열 배열, 변수를 선언하고 초기화한다.
String sa[] = {"This", "is", "a", "test", "string"};
String sb = "This is a book.";
%>
<HTML>
<HEAD>
<TITLE> String Class(2) </TITLE>
</HEAD>
<BODY>
[문자열 비교] <BR>
<%
out.println(sa[0].startsWith("Th"));
out.println("<BR>");
out.println(sa[3].endsWith("sT"));
out.println("<BR>");
for (i=0; i< 4; i++) {
    rv = sa[i].compareTo(sa[i+1]);
    if (rv <0) out.println("<");
    else if (rv >0) out.println(">");
    else out.println("=");
}
%>
<BR>
[문자열 검색]<BR>
'a'의 인덱스 : <%= sb.indexOf("a") %> <BR>
'i'의 인덱스 : <%= sb.indexOf("i") %> <BR>
[문자열 변환]<BR>
문자열 연결 : <%= sb.concat("That is a flower.") %> <BR>
문자열 대치 : <%= sb.replace('T','t') %> <BR>
대문자로 : <%= sb.toUpperCase() %> <BR>
소문자로 : <%= sb.toLowerCase() %> <BR>
[데이터형 변환]<BR>
정수형 리터럴 : <%= String.valueOf(342) %> <BR>
실수형 리터럴 : <%= String.valueOf(3.14159) %>
</BODY>
</HTML>