본문 바로가기
PROGRAMING📚/Java📑

Java :: 활용 -String

Ta이니 2024. 6. 25.
728x90
반응형

String

 

자바에서는 문자열을 == 로 비교하면 제대로된 값이 나오지 않는다

public class Ex01String {
  public static void main(String[] args) {
    String str1 = "hello";
    String str2 = new String("hello");
    System.out.println(str1 == str2); //false
  }
}

 

str1과 str2 에 "hello"라는 문자열을 넣어주었지만

str1 이랑 str2의 출력 결과가 false 로 출력되고 다르다고 출력된다

 

이를 확인하기 위해서

hashCode를 사용하여 객체의 중복 여부를 확인하거나 빠르게 검색 할 수 있다

public class Ex01String {
  public static void main(String[] args) {
    String str1 = "hello";
    String str2 = new String("hello");
    System.out.println(str1 == str2); //false
    System.out.println(str1.hashCode());
    System.out.println(str2.hashCode());
  }
}

package p06_javalang;

public class Ex01String {
  public static void main(String[] args) {
    String str1 = "hello";
    String str2 = new String("hello");
    System.out.println(str1 == str2); //false
    System.out.println(System.identityHashCode(str1));
    System.out.println(System.identityHashCode(str2));
  }
}

 


hashCode와 identityHashCode의 차이점

  1. 의미와 목적:
    • hashCode: 객체의 논리적 동등성을 확인하기 위해 사용됩니다. 컬렉션 프레임워크에서 객체를 효율적으로 저장하고 검색하는 데 사용됩니다.
    • identityHashCode: 객체의 물리적 동등성을 확인하기 위해 사용됩니다. 객체의 본래 해시 코드를 반환하여, 오버라이딩된 hashCode 메서드의 영향을 받지 않습니다.
  2. 오버라이딩 가능 여부:
    • hashCode: 서브클래스에서 오버라이딩 할 수 있습니다.
    • identityHashCode: 오버라이딩 할 수 없습니다. 항상 Object 클래스의 기본 구현을 사용합니다.
  3. 사용 예:
    • hashCode: 컬렉션 프레임워크에서 객체의 해시 기반 자료구조에 사용됩니다.
    • identityHashCode: 동일한 객체인지 확인할 때 사용됩니다.

이 두 메서드를 적절히 활용하면 객체의 논리적 동등성과 물리적 동등성을 모두 올바르게 처리할 수 있습니다

 

package p06_javalang;

public class Ex01String {
  public static void main(String[] args) {
    String str1 = "hello";
    String str2 = new String("hello");
    System.out.println(str1 == str2); //false
    System.out.println(System.identityHashCode(str1));
    System.out.println(System.identityHashCode(str2));
    System.out.println(str1.equals(str2));
  }
}

 

Instance를 사용해서 선언하면

 

public class Ex01String {
  public static void main(String[] args) {
    String str1 = "hello";
    String str2 = new String("hello");
    String str3 = "hello";
    String str4 = String.valueOf("hello");
    
    System.out.println(str1 == str2); //false
    System.out.println(str1 == str3); //false
    System.out.println(str1 == str4); //false
    System.out.println(str1.hashCode());
    System.out.println(str2.hashCode());
    System.out.println(str3.hashCode());
    System.out.println(System.identityHashCode(str1));
    System.out.println(System.identityHashCode(str2));
    System.out.println(System.identityHashCode(str3));
    System.out.println(str1.equals(str2));
  }
}

 

constant pool str1의 변수가 가리키는 "hello"를 가져옴 라는 문자 

System.out.println("str1.intern(): "+str1.intern());

str1.charAt('위치값') 

//배열은 length , string 은 length()
 for (int i = 0; i < str1.length(); i++) {
      if(i!=0) System.out.print(",");
      System.out.print(str1.charAt(i)); //한자씩 접근
    }

 

System.out.println(str1.compareTo("world"));

문자 연결하기 

System.out.println(str1.concat("world"));

str1안에 hell 이 들어있는가

System.out.println(str1.contains("hell"));

str1의 시작이 he 인가

System.out.println(str1.startsWith("he"));

 

str1의 끝이 lo 인가

System.out.println(str1.endsWith("lo"));

 

String.indexOf()

int indexOf(int ch): 문자열에서 특정 문자의 처음 나타나는 위치를 반환합니다.
int indexOf(int ch, int fromIndex): 특정 위치부터 시작하여 문자의 처음 나타나는 위치를 반환합니다.
int indexOf(String str): 문자열에서 특정 문자열의 처음 나타나는 위치를 반환합니다.
int indexOf(String str, int fromIndex): 특정 위치부터 시작하여 문자열의 처음 나타나는 위치를 반환합니다.

 

 

 

str1에서 ll 의 위치 값을 표현

System.out.println(str1.indexOf("ll"));

 

System.out.println(str1.indexOf("l",3));

 

String.lastIndexOf()

System.out.println(str1.lastIndexOf("l"));

 

String.replace()

l을 k로 변경

System.out.println(str1.replace("l", "k"));

 

String.split()

공백을 만나기 전까지의 글을 나누어서 arr[] 배열안에 넣어서 출력하는 방법

String[] arr = "Passion is genesis of genius".split(" ");
System.out.println(Arrays.toString(arr));

 

 

String substring(int startIndex)

String substring(int startIndex, int endIndex)

 

String fileName="abc.index.html"; 라는 문자열에서 html이라는 문자를 출력하는 방법

String fileName="abc.index.html";
System.out.println(fileName.substring(fileName.lastIndexOf(".")+1));

String fileName="abc.index.html"; 라는 문자열에서 index 이라는 문자를 출력하는 방법

System.out.println(fileName.substring(fileName.indexOf(".")+1, fileName.lastIndexOf(".")));

toUpperCase()/ toLowerCase()

System.out.println("hello world".toUpperCase());
System.out.println("hello world".toLowerCase());

String.trim()

좌우 공백 없애기

System.out.println(" hello world ".trim());

String.valueOf()

2진수, 8진수, 16진수를 10진수로 표기하기

    System.out.println(String.valueOf(0010)); //2
    System.out.println(String.valueOf(0b100)); //8
    System.out.println(String.valueOf(0xa0)); //16

StringJoiner

    //  String[] arr = "Passion is genesis of genius".split(" ");
    StringJoiner sj = new StringJoiner(",","*","*");
    for(String s: arr){
      sj.add(s);
    }
    System.out.println(sj.toString());

 


StringBuffer

 

String이 문자열 선언시 크기가 한정적이다 

그래서 문자열의 수정, 삽입, 삭제가 용이한 StringBuffer를 사용한다

 

같은 hello 라는 문자를 capacity와 length를 출력해보면 다음과 같이 출력된다

public class Ex02StringBuffer {
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("hello");
    System.out.println(sb.length());
    System.out.println(sb.capacity());
  }
}

length는 길이를 의미하고 capacity 는 용량을 의미한다

public class Ex02StringBuffer {
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("hello");
    System.out.println(sb.hashCode());
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    sb.append(" world");
    System.out.println(sb);
    System.out.println(sb.hashCode());
  }
}

해쉬 코드는 동일 하다는 것을 확인 할 수있다

 

System.out.println(sb.delete(4,6));

System.out.println(sb.insert(4,"o "));

문자열 거꾸로 출력하기

System.out.println(sb.reverse());

StringBuffer sb2= new StringBuffer("나랏말싸미 뒹국에 달아 백성이 이르고저 할배");
System.out.println(sb2.reverse());


 

public class Ex03ObjectMath {
  public static void main(String[] args) {
    System.out.println(Math.abs(-10));//10
    System.out.println(Math.abs(10.1)); //절상//10.1
  }
}

 

 

System.out.println(Math.floor(10.1)); //절삭 //10.0

 

System.out.println(Math.round(0.5)); //1
System.out.println(Math.round(-1.5));//-1

 

int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
  arr[i] =(int)(Math.random()*5)+1;
}
System.out.println(Arrays.toString(arr));

 

int max = arr[0];
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
  max = Math.max(max, arr[i]);
  min = Math.min(min, arr[i]);
}
System.out.println(max +"/"+min);

 

숫자를 문자열로 바꿈

System.out.println(Integer.toBinaryString(10)); //2진수의 문자로 표현
System.out.println(Integer.toOctalString(10));
System.out.println(Integer.toHexString(10));

문자열을 숫자로 변경하는 방법

System.out.println(Integer.parseInt("10"));
System.out.println(Integer.parseInt("1010",2)); // 2진법으로 
System.out.println(Integer.parseInt("1010",8)); // 8진법으로 
System.out.println(Integer.parseInt("1010",16)); // 16진법으로 

 

728x90
반응형

댓글