Day 24 (23.01.30)

Jane·2023년 1월 30일
0

IT 수업 정리

목록 보기
24/124

1. String 클래스 안의 여러 가지 함수들

Day 23에서 이어서 작성

1-1. substring (문자열 자르기)

  • substring 함수는 오버로딩이 적용되었다.
public class StringPractice {
	public static void main(String[] args) {
		String str = "abcdefg";
		System.out.println(str.substring(2));
        // index 지점부터 시작
		System.out.println(str.substring(2,4));
        // beginIndex부터 시작, endIndex에서 그만 출력
	}
}

[Console]
cdefg (매개변수 1개인 코드)
cd (매개변수가 2개인 코드)


String 클래스 :: substring(beginIndex)

public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = length() - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        if (beginIndex == 0) {
            return this;
        }
        return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
                          : StringUTF16.newString(value, beginIndex, subLen);
    }

String 클래스 :: substring(beginIndex, endIndex)

 public String substring(int beginIndex, int endIndex) {
        int length = length();
        checkBoundsBeginEnd(beginIndex, endIndex, length);
        int subLen = endIndex - beginIndex;
        if (beginIndex == 0 && endIndex == length) {
            return this;
        }
        return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
                          : StringUTF16.newString(value, beginIndex, subLen);
    }

1-2. 문자열 비교하기

  • equals() - String 비교, boolean 자료형 (Day 23 참고)
  • compareTo() - String 비교, int 자료형 (숫자로 비교한다)
  • compareToIgnoreCase() - String 비교, int 자료형 / 대소문자 무시

public class StringPractice {

	public static void main(String[] args) {
		String str1 = "Lexicographically";
		String str2 = "lexicographically";
		int cmp;

		if (str1.equals(str2)) {
			System.out.println("두 문자열은 같습니다.");
		} else {
			System.out.println("두 문자열은 다릅니다.");
		}

		cmp = str1.compareTo(str2);
		if (cmp == 0) {
			System.out.println("두 문자열은 같다.");
		} else if (cmp < 0) {
			System.out.println("사전의 앞에 위치하는 문자 : " + str1);
		} else {
			System.out.println("사전의 앞에 위치하는 문자 : " + str2);
		}
		
		if(str1.compareToIgnoreCase(str2) == 0) {
			System.out.println("두 문자열은 같습니다.");
		} else {
			System.out.println("두 문자열은 다릅니다.");
		}
	}

}

[Console]
두 문자열은 다릅니다.
사전의 앞에 위치하는 문자 : Lexicographically
두 문자열은 같습니다.


String 클래스 :: compareTo

  • 양수가 나오면 비교군이 앞으로, 본인이 뒤로
    음수가 나오면 본인이 앞으로, 비교군이 뒤로
    public int compareTo(String anotherString) {
        byte v1[] = value;
        byte v2[] = anotherString.value;
        if (coder() == anotherString.coder()) {
            return isLatin1() ? StringLatin1.compareTo(v1, v2)
                              : StringUTF16.compareTo(v1, v2);
        }
        return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
                          : StringUTF16.compareToLatin1(v1, v2);
     }

StringLatin1 클래스 :: compareToUTF16, compareToUTF16Values

  • compareToUTF16() : 길이를 구하고 UTF16Values 실행
  • compareToUTF16Values() : 바이트코드로 저장된 String 값을 비교하기
    public static int compareToUTF16(byte[] value, byte[] other) {
        int len1 = length(value);
        int len2 = StringUTF16.length(other);
        return compareToUTF16Values(value, other, len1, len2);
    }
    
        private static int compareToUTF16Values(byte[] value, byte[] other, int len1, int len2) {
        int lim = Math.min(len1, len2);
        for (int k = 0; k < lim; k++) {
            char c1 = getChar(value, k);
            char c2 = StringUTF16.getChar(other, k);
            if (c1 != c2) {
                return c1 - c2;
            }
        }
        return len1 - len2;
    }

StringUTF16 클래스 :: compareToLatin1

  • compareToUTF16 실행한 결과값의 부호를 변환
public static int compareToLatin1(byte[] value, byte[] other) {
        return -StringLatin1.compareToUTF16(other, value);
    }

String 클래스 :: compareToIgnoreCase

public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }

1-3. valueOf()

  • 모든 자료형을 전부 문자열로 바꾼다.
  • static과 오버로딩이 적용되었다.
  • println()에도 valueOf()가 들어가있다. (Day 21 참고)

public class StringPractice {

	public static void main(String[] args) {
		double e = 2.718281;
		String se = String.valueOf(e);
		System.out.println(se);
	}

}

String 클래스 :: valueOf()

	public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }

    public static String valueOf(char c) {
        if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
            return new String(StringLatin1.toBytes(c), LATIN1);
        }
        return new String(StringUTF16.toBytes(c), UTF16);
    }

    public static String valueOf(int i) {
        return Integer.toString(i);
    }

    public static String valueOf(long l) {
        return Long.toString(l);
    }

    public static String valueOf(float f) {
        return Float.toString(f);
    }

    public static String valueOf(double d) {
        return Double.toString(d);
    }

2. 문자열 더하기 연산

  • 연산을 하기 위해서는 앞의 자료형과 뒤의 자료형을 맞춰야 한다.
  • 문자열과 다른 자료형의 형변환은 문자열 쪽으로 해준다.
  • 더하기 연산(+)은 concat()로 바뀐다.
  • 자료형이 다른 것은 valueOf()로 맞춰준다.
  • String을 계속 결합하게 되면 쌍따옴표로 선언한 문자열들은 모두 메모리에 올라가게 된다.

3. StringBuilder

  • 문자열을 결합할 때 String을 사용하게 되면, 모든 String들이 모두 메모리에 올라가게 되기 때문에 메모리 낭비를 유발하게 된다.
  • String으로 인해 발생하는 메모리 낭비를 최소화하기 위해 StringBuilder 클래스를 제공한다. (Mutable)
  • StringBuilder는 객체 생성으로만 만들 수 있다. (String처럼 쌍따옴표로 하는 static 선언은 불가능)

public class StringPractice {

	public static void main(String[] args) {
		StringBuilder stbuf = new StringBuilder("123");
		System.out.println(stbuf.toString());
		
		stbuf.append(45678); // 이어붙이기
		System.out.println(stbuf.toString());
		
		stbuf.delete(0, 2); // 해당하는 범위 지우기
		System.out.println(stbuf.toString());
		
		stbuf.replace(0,3,"AB"); // 해당하는 범위 대체하기
		System.out.println(stbuf.toString());
		
		stbuf.reverse(); // 거꾸로 출력하기
		System.out.println(stbuf.toString());
		
		String sub = stbuf.substring(2,4); // substring 출력하기
		System.out.println(sub);
		
	}

}

[Console]
123 // new
12345678 // append
345678 // delete
AB678 // replace
876BA // reverse
6B // substring

  • 문자열을 이용하여 반복문을 오래 돌리게 될 경우, StringBuilder를 써서 메모리 소모를 줄일 수 있다.

4. 포맷 형식으로 출력하기 : printf


public class JavaPractice {

	public static void main(String[] args) {
		System.out.printf("정수는 %d, 실수는 %.2f, 문자는 %c", 12, 24.5, 'A');
	}
}

[Console]
정수는 12, 실수는 24.50, 문자는 A

5. 콘솔에 입력하기

5-1. Scanner 클래스

  • nextInt() : space(공백, 띄어쓰기)를 기준으로 int 자료형인 숫자를 담는 함수
import java.util.Scanner;

public class ScannerPractice {

	public static void main(String[] args) {
		String source = "1 3 5";
		Scanner sc = new Scanner(source);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		int num3 = sc.nextInt();
		int sum = num1 + num2 + num3;
		System.out.println(num1 + "+" + num2 + "+" + num3 + "=" + sum);
	}

}

[Console]
1+3+5=9

5-2. 키보드 입력하기

System 클래스 :: in (InputStream)

public static final InputStream in = null;
  • System.in : 사용자가 직접 키보드로 입력할 수 있도록 한다.
    ('InputStream' 참조형 데이터 타입 / static / final)
import java.util.Scanner;

public class ScannerPractice {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		int num3 = sc.nextInt();
		int sum = num1 + num2 + num3;
		System.out.println(num1 + "+" + num2 + "+" + num3 + "=" + sum);
	}

}

5-3. 문자열 입력하기

  • nextLine() : 문자열을 입력받는 함수
import java.util.Scanner;

public class JavaPractice {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("문자열 입력 : ");
		String str1 = sc.nextLine();
		System.out.print("문자열 입력 : ");
		String str2 = sc.nextLine();
		
		System.out.printf("%s \n", str1);
		System.out.printf("%s \n", str2);
	}

}

6. 예제

6-1. 키보드를 입력받기 + 국영수 점수 총합 평균 학점

import java.util.Scanner;

class Grade{
	private int kor;
	private int eng;
	private int math;

	
	public void setKor() {
		Scanner sc = new Scanner(System.in);
		System.out.print("국어 : ");
		this.kor = sc.nextInt();
	}
	
	public void setEng() {
		Scanner sc = new Scanner(System.in);
		System.out.print("영어 : ");
		this.eng = sc.nextInt();
	}
	
	public void setMath() {
		Scanner sc = new Scanner(System.in);
		System.out.print("수학 : ");
		this.math = sc.nextInt();
	}
	
	public int getSum() {
		return kor + eng + math;
	}
	
	public double getAvg() {
		return getSum() / 3.0;
	}

	public char getGrade() {
		char ch = '가';
		if(getAvg() >= 90) {ch = '수';}
		else if(getAvg() >= 80) {ch = '우';}
		else if(getAvg() >= 70) {ch = '미';}
		else if(getAvg() >= 60) {ch = '양';}
		else {ch = '가';}
		
		return ch;
	}
	
	public void show() {
		System.out.println("총점 : " + getSum());
		System.out.println("평균 : " + getAvg());
		System.out.println("학점 : " + getGrade());
	}
	
	
}

public class JavaPractice {

	public static void main(String[] args) {
		Grade a = new Grade();
		a.setKor();
		a.setEng();
		a.setMath();
		a.show();
		
	}

}

6-2. 문자열의 자음과 모음 개수

import java.util.Scanner;

class InputSystem {
	String str = null;

	public void getString() { // 문자 입력받기
		Scanner sc = new Scanner(System.in);
		this.str = sc.nextLine();
	}

	public int getLength() { // 문자의 길이 구하기
		int length = 0;
		if (str == null) {
			length = 0;
		} else {
			length = str.length();
		}
		return length;
	}

	public int getCount() { // 모음 개수 세기
		int count = 0;

		// a,e,i,o,u, A,E,I,O,U 개수 세기
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o'
					|| str.charAt(i) == 'u' || str.charAt(i) == 'A' || str.charAt(i) == 'E' || str.charAt(i) == 'I'
					|| str.charAt(i) == 'O' || str.charAt(i) == 'U') {
				count++;
			}
		}

		return count;
	}

	public int getSpace() {
    // 공백은 알파벳이 아니므로, 문자열 안에 공백의 개수는 제외한다
		int space = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ' ') {
				space++;
			}
		}
		return space;
	}

	public void show() { // 출력하기
		System.out.println("자음 개수 : " + (getLength() - getCount() - getSpace()));
		System.out.println("모음 개수 : " + getCount());

	}

}

public class StringPractice {

	public static void main(String[] args) {
		InputSystem input = new InputSystem();
		input.getString();
		input.show();

	}

}

[Console]
(입력) Alice in Wonderland
자음 개수 : 10
모음 개수 : 7

profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글