[문풀] String(repeating:count:)

Kiwi·2024년 3월 19일

Algorithm

목록 보기
1/17
post-thumbnail

⚙️ 핸드폰 번호 가리기

제일 처음 생각한 방법은 먼저 phone_number 문자열의 길이에서 4를 뺀 값을 구하고 그 값만큼 *를 반복하고 뒤에 문자열을 덧붙이는 방법을 생각했다. 그래서 코드를 다음과 같이 구현했다.

func solution(_ phone_number:String) -> String {
    var exceptLastFour = phone_number.count - 4
    var result = exceptLastFour * "*" + phone_number.suffix(4) //Cannot convert value of type 'String' to expected argument type 'Int'
    return result
}

그런데 여기서 var result = exceptLastFour * "*" + phone_number.suffix(4) 부분에서 Cannot convert value of type 'String' to expected argument type 'Int' 라는 에러가 났다. 이유는 string의 반복을 단순히 *(곱셈연산)으로 할 수 없기 때문이다.

찾아보니 String(repeating:count:) 라는 생성자가 있었다. 개념이 낯설을 수 있는데 생성자는 객체를 초기화할때 사용하는 특별한 메서드였다! 이 경우 String이라는 구조체의 생성자로 반복된 문자열을 생성하는데 사용되는 것이다!!😮 이 생성자를 사용하는 방법은 매우 간단하다. *를 4번 생성하고 싶으면

let repeatedStars = String(repeating: "*", count: 3)
print(repeatedStars) // ****

다음과 같이 작성하면 된다.

위의 메서드를 이용해서 다시 작성한 코드는 다음과 같다.

다른 사람들의 풀이를 보니 내가 제출한 정답과 방법은 같으나 훨씬 더 간결하게 작성하신 분들이 많았다!!!

func solution(_ phone_number:String) -> String {
    return String(repeating:"*", count:phone_number.count-4)+phone_number.suffix(4)
}

이렇게 작성하면 한줄로 끝난다..!!!😅

📝 String끼리의 연산

이 기회에 string끼리의 연산에 대해 추가적으로 정리해 보았다.

string끼리의 + : 가능

let str1 = "hello"
let str2 = "swift"
print(str1+str2)	//helloswift

string끼리의 - : 불가능
이건 생각해보면 변수가 많고 뺄셈자체가 불가능할 수 있어서 안되는 것이 가능하다.

var str1 = "hello swift"
var str2 = "swift"
print(str1 - str2)	//Binary operator '-' cannot be applied to two 'String' operands

만약 string에서 특정 문자열을 빼고 싶다면 다음과 같은 방법을 사용해야 한다.

let startIndex = str1.index(str1.startIndex, offsetBy: 6)
let endIndex = str1.endIndex
str1.removeSubrange(startIndex..<endIndex)  //"hello "

removeSubrange(startIndex..<endIndex) 메서드는 지정한 index 범위 만큼의 string을 제거해준다.

apple 공식문서 - swift/string/init(repeating:count:)

profile
🐣 iOS Developer

0개의 댓글