JAVA에서 문자열을 다루는 가장 기본적인 클래스
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
//char[] -> String
char[] hello = {'h', 'e', 'l', 'l', 'o'};
String helloStr = new String(hello);
System.out.println(helloStr); //hello
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)String str4 = "apple";
System.out.println(str4.startsWith("ap")); // true
System.out.println(str4.endsWith("l")); // false
- 수정 가능한 문자열 클래스
- 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 (공백있음)