1. String 관련 함수
package ex08;
// String 관련된 함수 다 사용해보기
public class Str01 {
public static void main(String[] args) {
// 1. 문자열의 길이
String s1 = "abcd";
System.out.println("s1 length : " + s1.length());
// 2. 특정 index의 문자 확인하기
String s2 = "abcd";
System.out.println("s2 charAt(2) : " + s2.charAt(2));
// 3. 문자열 비교
System.out.println("abcd".equals("abcd"));
// 4. 문자열 추출
// 검증 필요 1. 첫번째 인덱스가 0이 맞는지 2. endIndex가 마지막이 맞는지 그 직전인지
// 마우스를 함수 위에 올려서 문서 확
String s3 = "abcd";
System.out.println(s3.substring(1, 3));
// 5. 문자열 검색
String s4 = "abcd";
System.out.println(s4.indexOf("c"));
// 6. 문자열 포함 여부 (true/false)
String s5 = "abcd";
System.out.println(s5.contains("k"));
// 7. 문자열 대소문자 변경
String s6 = "Abcd";
System.out.println(s6.toUpperCase());
System.out.println(s6.toLowerCase());
// 8. 문자열 치환 (replace, replaceAll)
int age = 10;
String s7 = "내 나이는 $age고 난 내나이 $age가 좋아".replace("$age", age + ""); //묵시적 형변환
System.out.println(s7);
// 9. 앞뒤 공백 제거 (trim)
String s8 = " abcd ";
System.out.println(s8.trim());
// 10. 문자열 분리 (split)
String s9 = "ab:cd:ef";
String[] r9 = s9.split(":");
System.out.println(r9[0]);
System.out.println(r9[1]);
System.out.println(r9[2]);
}
}

2. 부산에 사는 고객은 몇 명인가요? (String 관련 함수 활용 문제)
package ex08;
public class Str02 {
public static void main(String[] args) {
String nums = """
031)533-2112,
02)223-2234,
02)293-4444,
051)398-3434,
02)498-3434,
051)398-3434,
043)3222-3434
""";
// 부산에 사는 고객(051을 포함하는 전화번호) 수
int count = 0;
String[] splitNums = nums.split(",\n");
String[] newNums = new String[splitNums.length];
for (int i = 0; i < splitNums.length; i++) {
int idx = splitNums[i].indexOf(")");
newNums[i] = splitNums[i].substring(0, idx);
//newNums[i] = newNums[i].trim(); // split할 때 ")"로만 할 경우 trim 필요!
if (newNums[i].equals("051")) {
count++;
}
}
System.out.println("부산에 사는 고객은 $count명입니다".replace("$count", count + ""));
// 부산에 사는 고객은 몇명인가요?
// 1. split(",\n")로 String[] splitNums[]로 옮기기
// 2. splitNums[] for문 돌면서 indexOf(")") 위치 찾아서 substring으로 지역번호 추출해서 지역번호만 newNums[]로 옮기기
// 3. newNums[] for문 돌면서 051 지역번호를 equals로 확인 or contains로 확인하여 고객수를 int count변수에 누적
// 4. count 변수 출력
}
}

Share article