![[자바 #9] 문자열(String) 타입](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog-custom%3Ftitle%3D%255B%25EC%259E%2590%25EB%25B0%2594%2B%25239%255D%2B%25EB%25AC%25B8%25EC%259E%2590%25EC%2597%25B4%2528String%2529%2B%25ED%2583%2580%25EC%259E%2585%26tag%3DTemplate%2B1%26description%3D%26template%3D3%26backgroundImage%3Dhttps%253A%252F%252Fsource.inblog.dev%252Fog_image%252Fdefault.png%26bgStartColor%3D%25233f0707%26bgEndColor%3D%25233f0707%26textColor%3D%2523000000%26tagColor%3D%2523000000%26descriptionColor%3D%2523000000%26logoUrl%3D%26blogTitle%3DGyeongwon%2527s%2Bblog&w=2048&q=75)
자바의 문자열은 String 객체로 생성된다.
1. 문자열 비교
String name1 = "홍길동";
String name2 = "홍길동";
name1과 name2 변수에는 동일한 String 객체의 번지가 저장된다.
System.out.println(name1 == name2); // true
String name1 = new String("홍길동");
String name2 = new String("홍길동");
String 변수에 문자열 리터럴을 대입하는 것이 일반적이지만,
new
연산자로 직접 String 객체를 생성하고 대입할 수 도 있다. new
연산자는 새로운 객체를 만드는 연산자로 객체 생성 연산자라고 한다. 이 경우에는 name1, name2 변수는 서로 다른 String 객체의 번지를 가진다.
System.out.println(name1 == name2); // false
동일한 String 객체든 다른 String 객체든 상관없이 내부 문자열만을 비교할 경우에는 String 객체의
equals()
메소드를 사용한다.boolean result = str1.equals(str2); // 문자열이 같은지 검사(대소문자 구분함)
2. 문자 추출
문자열에서 특정 위치의 문자를 얻고 싶다면
charAt()
메소드를 이용한다. charAt() 메소드는 매개값으로 주어진 인덱스의 문자를 리턴한다. String subject = "자바 프로그래밍";
char charValue = subject.charAt(3); // 프
3. 문자열 길이
length()
메소드를 사용한다. String subject = "자바 프로그래밍";
int length = subject.length(); // 8
4. 문자열 대체
replace()
메소드를 사용한다.String oldStr = "자바 프로그래밍";
String newStr = oldStr.replace("자바", "JAVA"); // JAVA 프로그래밍
5. 문자열 잘라내기
substring()
메소드를 사용한다.- substring(int beginIndex)
- substring(int beginIndex, int endIndex)
String ssn = "880815-1234567";
String firstNum = ssn.substring(0, 6); // 880815
String secondNum = ssn.substring(7); // 1234567
6. 문자열 찾기
indexOf()
메소드를 사용한다.String subject = "자바 프로그래밍";
int index = subject.indexOf("프로그래밍"); // 3
만약 주어진 문자열이 포함되어 있지 않으면 indexOf() 메소드는 -1을 리턴한다.
7. 문자열 분리
split()
메소드를 사용한다.String board = "번호, 제목, 내용, 성명";
String[] arr = board.split(",");
// arr[0]에 "번호" arr[1]에 "제목" ...
Share article