public class _01_String1 {
public static void main(String[] args) {
String s = "I like Java and Python and C.";
System.out.println(s); // I like Java and Python and C.
}
}
문자영를 클래스 타입이기에 여러 가지 메소드를 가지고 있다.
대표적으로 다음과 같은 '메소드'들이 있다
예시는 다음과 같다.
public class _01_String1 {
public static void main(String[] args) {
String s = "I like Java and Python and C.";
System.out.println(s);
// 문자열의 길이
System.out.println(s.length()); // 29
// 대소문자 변환
System.out.println(s.toUpperCase()); // 대문자로
System.out.println(s.toLowerCase()); // 소문자로
// 포함 관계
System.out.println(s.contains("Java")); // 포함된다면 true
System.out.println(s.contains("C#")); // 포함되지 않는다면 false
System.out.println(s.indexOf("Java")); // 위치 정보
System.out.println(s.indexOf("C#")); // 포함되지 않는다면 -1
System.out.println(s.indexOf("and")); // 처음 일치하는 위치 정보
System.out.println(s.lastIndexOf("and")); // 마지막 일치하는 위치 정보
System.out.println(s.startsWith("I like")); // 이 문자열로 시작하면 true (아니면 false)
System.out.println(s.endsWith(".")); // 이 문자열로 끝나면 true (아니면 false)
// 문자열 변환
System.out.println(s.replace(" and", ",")); // " and" 를 "," 로 변환
System.out.println(s.substring(7)); // 인덱스 기준 7부터 시작(이전 내용은 삭제)
System.out.println(s.substring(s.indexOf("Java")));
// "Java"가 시작하는 위치부터, "."이 시작하는 위치 바로 앞까지
System.out.println(s.substring(s.indexOf("Java"), s.indexOf("."))); // 시작 위치부터 끝위치 "직전"
// 공백제거
s = " I love Java ";
System.out.println(s);
System.out.println(s.trim()); // 앞뒤 공백 제거
// 문자열 결합
String s1 = "Java";
String s2 = "Python";
System.out.println(s1 + s2); // JavaPython
System.out.println(s1 + ", " + s2); // Java, Python
System.out.println(s1.concat(", ").concat(s2)); // Java, Python
}
}