본문 바로가기
JAVA

[JAVA] 자바 문자열(String) 함수

by Amy IT 2022. 5. 18.

String의 주요 함수들에 대해 알아보겠습니다.

 

 

valueOf : 문자열로 변환하여 반환합니다.

System.out.println(String.valueOf(10)+10); //1010

 

length : 문자열의 길이를 반환합니다.

String str="  hello  ";
System.out.println(str.length()); //9

 

trim : 문자열의 양쪽 공백을 없애줍니다.

String t="  hello  ";
System.out.println(t.trim()); //hello
System.out.println(t.trim().length());; //5

 

substring : 지정한 범위의 문자열을 추출합니다. start번호부터, end번호의 -1 까지 추출합니다. 첫 글자로 인덱스 0번부터 시작합니다. 끝나는 지점을 지정하지 않으면 지정한 시작값부터 끝까지 반환합니다.  

// 0,1,2,3,4
// h e l l o
String xyz ="helloworld";
String q = xyz.substring(3); 
System.out.println(q); // loworld
String q2 = xyz.substring(0,5);
System.out.println(q2); // hello

 

charAt : 지정한 인덱스 번호의 문자를 뽑아 반환합니다.

String s = "hello";
char x = s.charAt(0);
System.out.println(x); //h
System.out.println(s.charAt(1)); //e

 

concat : 문자열을 연결합니다.

String str1 = "hello";
String str2 = str1.concat("world"); 
System.out.println(str2); //helloworld

 

equals : 문자열을 비교하여 일치하는지 판단합니다.

String aaa ="Hello";
String aaa2 ="hello";
boolean result = aaa.equals(aaa2);
System.out.println(result); //false

 

equalsIgnoreCase : 대소문자 구분 없이 문자열을 비교하여 일치하는지 판단합니다.

boolean result2 = aaa.equalsIgnoreCase(aaa2);
System.out.println(result2); //true

 

contains : 문자열에 특정 문자열이 포함되어 있는지 판단합니다.

String s = "hello";
boolean kkk = s.contains("h");
System.out.println(kkk); //true

 

endsWith : 문자열이 특정 문자열로 끝나는지 판단합니다.

String s = "hello";
boolean kkk3 = s.endsWith("lo");
System.out.println(kkk3); //true

 

startsWith : 문자열이 특정 문자열로 시작하는지 판단합니다.

boolean kkk5 = "world".startsWith("w");
System.out.println(kkk5); //true

 

indexOf : 문자열에서 특정 문자의 인덱스 번호를 반환합니다. 없을 경우 -1을 반환합니다.

int index = "hello".indexOf("x");
System.out.println(index); // -1

 

isEmpty : 문자열이 공백인지 판단합니다.

System.out.println("".isEmpty()); //true

 

replace : 문자열에서 특정 문자를 다른 문자로 바꾸거나, 특정 문자열을 다른 문자열로 바꾸어 반환합니다.

System.out.println("abc".replace('a', 'A')); //Abc
System.out.println("abc".replace("ab", "xxx")); //xxxc

 

toUpperCase : 문자열을 대문자로 바꾸어 반환합니다.

System.out.println("abc".toUpperCase()); //ABC

 

toLowerCase : 문자열을 소문자로 바꾸어 반환합니다.

System.out.println("ABC".toLowerCase()); //abc

 

split : 특정 문자를 기준으로 문자열을 구분하여 배열로 반환합니다.

String str = "홍길동/이순신/유관순";
String [] names = str.split("/");
for (int i = 0; i < names.length; i++) {
	System.out.print(names[i]+" ");
} //홍길동 이순신 유관순

 

format : 특정 포맷에 맞는 문자열로 반환합니다.

String formatString = String.format("이름은 %s, 나이는 %d, 키는 %.2f", "홍길동", 20, 180.2);
System.out.println(formatString); //이름은 홍길동, 나이는 20, 키는 180.20

 

 

이상으로 문자열과 관련된 주요 함수들을 정리해 보았습니다. 

 

 

댓글