프로그래머스 - 코딩 기초 트레이닝
8) 특정한 문자를 대문자로 바꾸기
영소문자로 이루어진 문자열 my_string과 영소문자 1글자로 이루어진 문자열 alp가 매개변수로 주어질 때, my_string에서 alp에 해당하는 모든 글자를 대문자로 바꾼 문자열을 return 하는 solution 함수를 작성해 주세요.
1 ≤ my_string의 길이 ≤ 1,000
my_string alp result
"programmers" "p" "Programmers"
"lowercase" "x" "lowercase"
입출력 예 #1
예제 1번의 my_string은 "programmers"이고 alp가 "p"이므로 my_string에 모든 p를 대문자인 P로 바꾼 문자열 "Programmers"를 return 합니다.
입출력 예 #2
예제 2번의 alp는 "x"이고 my_string에 x는 없습니다. 따라서 "lowercase"를 return 합니다.
func solution(my_string string, alp string) string {
alp_rune := []rune(alp)[0]
var result string = ""
count := 0
for _, char := range my_string {
if char == alp_rune {
result = strings.ReplaceAll(my_string, alp, strings.ToUpper(alp))
count++
}
result = my_string
}
return result
}
위에는 오답이었음
func solution(my_string string, alp string) string {
var result string
// Convert alp to uppercase
alpUpper := strings.ToUpper(alp)
for _, char := range my_string {
// Check if the character matches alp
if string(char) == alp {
// Append the uppercase version of alp to result
result += alpUpper
} else {
// Append the original character to result
result += string(char)
}
}
return result
}
import "strings"
func solution(my_string string, alp string) string {
answer := []string{}
for _, r := range my_string {
if string(r) == alp {
a := strings.ToUpper(string(r))
answer = append(answer, string(a))
} else {
answer = append(answer, string(r))
}
}
return strings.Join(answer, "")
}
1.rune 데이터 유형
Go에서 rune은 int32의 별칭임
문자열은 UTF-8로 인코딩되므로 rune을 사용하면 유니코드 문자로 나타낼 수 있음
예:) alp_rune := []rune(alp)[0]
rune(alp): alp 문자열을 rune 조각으로 변환/조각의 alp가 p인 경우 rune(alp)는 []rune{'p'}가 됨
사용하는 이유
1)유니코드 지원
2)문자열 조각: 문자열의 문자를 반복하거나 개별 문자를 기반으로 작업을 수행하는 경우 편리함
3)문자 수준 작업: 특정 문자 확인, 문자 발생 횟수 계산, 문자 교체 등 작업 수행 가능함
2.문자열 치환: strings.ReplaceAll()
1)func ReplaceAll(s, old, new string) string
예) strings.ReplaceAll()을 사용하여 하위 문자열 "hello"의 모든 항목을 "hi"로 바꾼다.
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello world, hello universe"
// Replace all occurrences of "hello" with "hi"
newStr := strings.ReplaceAll(str, "hello", "hi")
fmt.Println(newStr) // Output: hi world, hi universe
}
2)func ReplaceAll(s, old, new string, n int) string
import (
"fmt"
"strings"
)
func main() {
str := "hello hello hello"
// Replace all occurrences of "hello" with "hi"
newStr := strings.ReplaceAll(str, "hello", "hi")
fmt.Println(newStr) // Output: hi hi hi
// Replace only the first occurrence of "hello" with "hi"
newStr2 := strings.ReplaceAll(str, "hello", "hi", 1)
fmt.Println(newStr2) // Output: hi hello hello
// Don't replace any occurrences
newStr3 := strings.ReplaceAll(str, "hello", "hi", 0)
fmt.Println(newStr3) // Output: hello hello hello
}
1.rune 타입으로 선언 및 사용하는 방법을 알고 있는가
2.대문자로 바꾸는 방법을 알고 있는가?
:strings.ToUpper(a)
3.문자열 단어 찾아서 바꾸는(치환) 방법을 알고 있는가
:strings.ReplaceAll("문자열", "찾고 싶은 문자열", "바꾸고 싶은 문자열", -1)
1.Nc
2.Y
3.N