Epistemology

The truth is out there.

러스트에서 `String`을 이용할 때, 생기는 유니코드 문제점

2021-09-10

러스트에서 문자열을 다루는 방법은 String을 이용하는 것입니다. 그런데 이것을 이용하더라도 유니코드를 사용하는 경우 인텍싱이 다른 언어와 같이 명확하게 처리되지 않습니다. 다음 코드를 살펴봅시다.

 1fn main() {
 2let s1 = String::from("hello world!");
 3let hello = &s1[0..5];
 4let world = &s1[6..11];
 5println!("{}, {}", hello, world);
 6
 7let s1 = String::from("안녕 세계!");
 8let hello = &s1[0..6];
 9let world = &s1[7..13];
10println!("{}, {}", hello, world);
11
12let s1 = String::from("こんにちは世界!");
13let hello = &s1[0..15];
14let world = &s1[15..21];
15
16println!("{}, {}", hello, world);
17}

윗 코드를 실행하면 다음과 같은 결과 나옵니다. 앞에서 인텍싱하는 코드를 살펴보면 글자 수와 인덱싱 숫자가 맞지 않는 것을 알 수 있습니다.

1cargo run
2Compiling ownership v0.1.0 (/Users/jaehwan/git/rust/projects/ownership)
3Finished dev [unoptimized + debuginfo] target(s) in 0.39s
4Running `target/debug/ownership`
5hello, world
6안녕, 세계
7こんにちは, 世界

참고하세요!