[멋사 알고리즘 스터디] 23.09.23 - String 문자열

김민경·2023년 9월 23일

String 문자열 🗣️

프로그래밍 언어에서 문자열이라는 데이터를 저장하기 위해 String이라는 데이터 타입을 사용한다.
다른 언어와는 달리 Java에서의 String은 특별한 자료형으로 취급되어 여러 유의사항들이 존재한다.

우선 String에 대해 알아보자!


Java String의 특징

  1. String은 객체

    • int , char -> 기본형 변수
      String -> 참조형 변수

    즉, 스택 영역이 아닌 객체와 같이 힙에서 문자열 데이터가 생성되고 다뤄진다.

  2. String은 변경할 수 없다.

    String a = "Hello";
     a = a + "World";

    a는 변경된 것이 아닌
    새로운 힙 메모리에 "Hello World"를 따로 만든다.

  3. String을 선언하는 방법

    String str1 = "Hello"; //문자열 리터럴을 이용한 방식
    String str2 = new String("Hello"); //new 연산자를 이용한 방식

Java String 메소드

  1. equals()
    두 개의 문자열이 동일한 값을 가지고 있는지 비교
String a = "Hello";
String b = "Hello";
System.out.println(a.equals(b)); //true

참고로 '==' 연산자는 주소값을 비교해주기 때문에 값을 비교할 때는 equals()를 사용해야 한다.

  1. indexOf
    문자열에서 특정 문자가 시작되는 인덱스 리턴
String str1 = "abcdef";
System.out.println(str1.indexOf("b")); //1
  1. length()
    문자열의 길이 반환
String str1 = "I Love You";
System.out.println(str1.length()); //10
  1. substring()
    문자열 중 특정 부분을 뽑아낼 경우에 사용
String str1 = "Hello World";
System.out.println(str1.substring(6,11)); //World

substring(int startindex, int endindex)에서 startindex는 자를 문자열의 시작점과 endindex는 자를 문자열의 끝+1이 들어간다.

5.split()
지정한 문자로 문자열을 나눌 수 있다. 나눠진 부분들의 결과 값은 배열로 반환

String str1 = "1,2,3";
String [] string = str1.split(",");
for (String s : string){
	System.out.println(s);
}
//1
//2
//3
  1. trim()
    문자열의 시작과 끝에 있는 공백을 없애준다. 중간 공백은 없애주지 않는다.
String str1 = "       H ello W o rld       ";
System.out.println(str1.trim()); //H ello W o rld
  1. compareTo()
    두 개의 String을 사전적 방식으로 문자열 간 차이를 계산한다. ASCII코드의 값을 기준으로 비교하고, 같으면 0을 반환한다.
String a = "a"; //97
String b = "b"; //98
System.out.println(a.compareTo(b)); //97 - 98과 같음 따라서 -1
  1. contains()
    두 개의 String을 비교해서 비교대상 String을 포함하고 있으면 true, 다르면 false를 반환한다.
String str1 = "Hello, World";
System.out.println(str1.contains("World")); //true
  1. charAt()
    지정한 index번째에 문자를 반환한다.
String str1 = "abcdef";
System.out.println(str1.charAt(2)); //c
  1. toUpperCase() / toLowerCase()
    모두 대문자로 변경하거나, 모두 소문자로 변경할 때 사용한다.
String str1 = "abcd";
String str2 = "ABCD";
System.out.println(str1.toUpperCase()); //ABCD
System.out.println(str2.toLowerCase()); //abcd

문제풀이

[단어 정렬]
백준 1181번
https://www.acmicpc.net/problem/1181

import java.util.Arrays;
import java.util.Scanner;
//[문자열] 단어 정렬
class Words{
    String word;
    Words(String word){
        this.word=word;
    }
}
public class Main_1181 {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);

        int num = s.nextInt();
        s.nextLine();
        Words [] words = new Words[num];
        for (int i=0; i<num; i++){
            String word = s.nextLine();
            words[i] = new Words(word);
        }
        Arrays.sort(words, (w1, w2) ->
                w1.word.length() == w2.word.length()?
                        w1.word.compareTo(w2.word) : w1.word.length() - w2.word.length());
        //단어끼리 길이가 같다면 compareTo 함수를 통해 사전순으로 비교하여 정렬
        //단어끼리 길이가 다르다면 길이 순으로 정렬

        System.out.println(words[0].word);
        //처음 단어를 먼저 출력하고 아래에서는 다음 단어와 비교하면서 같지 않으면 다음 단어를 출력
        for (int i=0; i<words.length-1; i++){
            if (!words[i].word.equals(words[i+1].word)){
                System.out.println(words[i+1].word);
            }

        }

    }
}

Arrays.sort를 사용하여 어떤 배열을, 어떤 기준으로 정렬할 것인지 람다 함수로 지정할 수 있다.


[AC]
백준 5430번
https://www.acmicpc.net/problem/5430

import java.util.*;

public class Main_5430 {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);

        int T = s.nextInt();
        s.nextLine();
        for (int i=0; i<T; i++){
            boolean isReverse = false;
            boolean isEmpty = false;
            char [] p = s.nextLine().toCharArray();
            int n = s.nextInt();
            s.nextLine();

//            String a = s.nextLine();
//            String [] arr = a.substring(1,a.length()-1).split(",");
//
//            Deque<String> dq = new ArrayDeque<>(Arrays.asList(arr));
            //이런 형태면 비어있는 리스트가 들어왔을 때 [""]의 형태가 된다.

            StringTokenizer st = new StringTokenizer(s.nextLine(), "[],");
            //StringTokenizer에서 문자열을 특정 구분자를 기준으로 분리할 수 있다.
            Deque<Integer> dq = new ArrayDeque<>();

            for (int j=0; j<n; j++){
                dq.add(Integer.parseInt(st.nextToken()));
            }


            for (char c : p){
                if (c == 'R') isReverse = !isReverse;
                if (c == 'D'){
                    if (dq.isEmpty()) {
                        isEmpty = true;
                        break;
                    } else {
                        if (isReverse) dq.removeLast();
                        else dq.removeFirst();
                    }
                }
            }

            if (isEmpty) {
                System.out.println("error");
                continue;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            if (!dq.isEmpty()) {
                //덱이 비어 있으면 []만 출력 하도록 확인 해준다.
                if (isReverse) {
                    sb.append(dq.pollLast());
                    while (!dq.isEmpty()) {
                        sb.append(",").append(dq.pollLast());
                    }
                } else {
                    sb.append(dq.pollFirst());
                    while (!dq.isEmpty()) {
                        sb.append(",").append(dq.pollFirst());
                    }

                }
            }
            sb.append("]");

            System.out.println(sb);


        }
    }
}

해당 문제는 Deque를 사용하여 해결하였다.
StringTokenizer에서 문자열을 특정 구분자를 기준으로 분리할 수 있다는 것을 알았다.

profile
뭐든 기록할 수 있도록

0개의 댓글