본문 바로가기
프로그래머스 코딩테스트 연습

[프로그래머스 코테 c#] Lv0. 문자열 앞의 n글자

by 노재두내 2024. 2. 13.

문제 

문자열 my_string과 정수 n이 매개변수로 주어질 때, my_string의 앞의 n글자로 이루어진 문자열을 return 하는 solution 함수를 작성해 주세요.

 

 

using System;

public class Solution {
    public string solution(string my_string, int n) {
        string answer = "";
        return answer;
        
        for(int i=0;i<n;i++){
            Console.WriteLine(my_string[i]);
        }
    }
}

 

ㅠㅠ

WriteLine이 개행을 하는건지 까먹음

프로그래머스에서 쥐어준 answer을 활용해야하는건가?

my_string을 내 맘대로 배열로 해도되는건가? my_string[i] 

 

 

생각해보니 문제가 solution함수를 작성하라는거니까 answer을 return 하고 있기 때문에 따로 console.WriteLine이 필요없구나 생각이 들었따.

using System;

public class Solution {
    public string solution(string my_string, int n) {
        string answer = "";
        for(int i=0;i<n;i++){
            answer=my_string[i];
        return answer;
    }
}

이렇게 바꿔보았당

에러난듯

아 괄호 하나 빼먹음

또 오류 문자열 하나씩만 되는것임 아 이해

my_string[i]를 for문을 돌면서 answer에 넣어봤자

예를 들어 my string이 yeomseyoung이라고 쳤을 때 y였다가 다음엔 e 였다가 이렇게 되는것 뿐이다. 그래서 그것들을 연결해줘야하니까 +=가 생각이 났다.

using System;

public class Solution {
    public string solution(string my_string, int n) {
        string answer = "";
        for(int i=0;i<n;i++){
            answer+=my_string[i];
        }
        return answer;
    }
}

헤헤 앗싸 ~^^

 

 

다른사람 풀이

int i = 0;
        string answer = "";
        while(i < n)
        {
            answer += my_string[i];
            i++;
        }
        return answer;

while문을 쓴사람도 있고

public class Solution {
    public string solution(string my_string, int n) {
        return my_string.Substring(0, n);
    }
}

지정된 문자 위치에서 시작하여 문자열의 끝 전에 끝나는 부분 문자열을 추출하려면 메서드를 호출합니다

 Substring(Int32, Int32) .