[Algorithm] 문자열 (0705)

왕감자·2024년 7월 5일

KB IT's Your Life

목록 보기
72/177

<문자열>

String 클래스

JAVA에서 문자열을 다루는 가장 기본적인 클래스

형변환

1) 문자열로 형변환

String.valueOf()

//String으로 형변환
int a = 3;
float b = 2.5f;
String num1 = String.valueOf(a);
String num2 = String.valueOf(b);

System.out.println(num1.getClass().getName());
System.out.println(num2.getClass().getName());
// java.lang.String

2) char[] ➔ 문자열

//char[] -> String
char[] hello = {'h', 'e', 'l', 'l', 'o'};
String helloStr = new String(hello);
System.out.println(helloStr); //hello

3) 문자열 ➔ 숫자

String input = "-5";
int negNum = Integer.parseInt(input); // -5
String input2 = "10.5";
double realNum = Double.parseDouble(input2); // 10.5

불변성

한 번 생성된 String 객체는 수정할 수 없음

String str = "hello world";
str = "hello new world";
System.out.println(str); // hello new world
// 가르키는 주소 값이 달라지는 것
  • String.replace()
    • 새로운 객체를 생성하기 때문에 결과 값을 저장해야 함
	String old = "hello world";
    old.replace('o', 'a'); // 결과 값 저장 안됨
	String replaced = old.replace('o', 'a'); 	// 새 문자열 반환
	System.out.println(replaced); // hella walrd

  • 문자열 비교
    • == : 주소 값이 같은지 비교
    • euqals() : 같은 값을 가지고 있는지 비교
    	String str1 = "50";
        String str2 = String.valueOf(50);
        System.out.println(str1 == str2); //false
        System.out.println(str1.equals(str2)); //true

메소드

  • indexOf(char), lastIndexOf(char)
    : 특정 문자의 첫번째, 마지막 인덱스 반환
String app = "apple";
int first = app.indexOf('p'); // 1
int last = app.lastIndexOf('p'); // 2
  • replaceAll(정규표현식, String)
    : 정규 표현식에 매치되는 부분을 새로운 문자열로 교체
String str3 = "apple";
String replaced3 = str3.replaceAll("[ap]", "z");
System.out.println(replaced3); // zzzle
  • startsWith(String), `endsWith(String)
    : 특정 문열로 시작하거나 끝나면 true
String str4 = "apple";
System.out.println(str4.startsWith("ap")); // true
System.out.println(str4.endsWith("l")); // false

StringBuilder

  • 수정 가능한 문자열 클래스
  • String 클래스와는 다르게 변경 메소드를 호출해도 새로운 인스턴스를 생성하지 않고 기존 값 수정
StringBuilder sb = new StringBuilder();
sb.append("hello ");
sb.append("world!");
System.out.println(sb); //hello world!

StringBuilder sb2 = new StringBuilder("initial String"); // 초기값 설정
System.out.println(sb2); // initial String

메소드

  • reverse()
    : 문자열 뒤집기
StringBuilder sb = new StringBuilder("hello world!);
sb.reverse();
ystem.out.println(sb); //!dlrow olleh
  • append(String)
    : 새 문자열 추가
StringBuilder sb = new StringBuilder();
sb.append("hello ");
sb.append("world!");
System.out.println(sb); //hello world!
  • insert(idx, String)
    : 특정 인덱스에 문자열 삽입
StringBuilder sb3 = new StringBuilder("apple");
sb3.insert(2, "JAVA");
System.out.println(sb3); // apJAVAple
  • delete(start, end)
    : 특정 범위 문자들 삭제
StringBuilder sb4 = new StringBuilder("Hellappo World!");
sb4.delete(4, 7);
System.out.println(sb4); // Hello World!
  • deleteCharAt(idx)
    : 특정 인덱스 문자 하나 삭제
StringBuilder sb5 = new StringBuilder("ABpple");
sb5.deleteCharAt(1);
System.out.println(sb5); // Apple
  • setCharAt(idx, char)
    : 특정 인덱스 문자 교체
StringBuilder sb6 = new StringBuilder("Hello, borld");
sb6.setCharAt(7, 'w');
System.out.println(sb6); // Hello, world
  • setLength(int)
    : 문자열 길이를 변경
    - 새로운 길이가 기존 길이보다 작 : 나머지 부분 잘림
    - 새로운 길이가 기존 길이보다 길 : 빈 공간 공백으로 채워짐
StringBuilder sb7 = new StringBuilder("hello world");
sb7.setLength(5);
System.out.println(sb7); // hello
        
StringBuilder sb8 = new StringBuilder("hello world");
sb8.setLength(16);
System.out.println(sb8); // hello world     (공백있음)

0개의 댓글