본문 바로가기

개발 이야기/Rust 언어 이야기

rust 에서 String 에서 요소 하나 하나를 index 인덱싱 하는 방법

728x90

Rust 언어에서 String 의 요소 하나하나를 index 인덱싱 하는 방법에 관련된 

좋은 예제 샘플 링크를 공유합니다.

:=> stackoverflow.com/questions/24542115/how-to-index-a-string-in-rust

 

예제 샘플은 다음과 같습니다.

이런 코드에서 

fn is_palindrome(num: u64) -> bool {
    let num_string = num.to_string();
    let num_length = num_string.len();

    for i in 0 .. num_length / 2 {
        if num_string[i] != num_string[(num_length - 1) - i] {
            return false;
        }
    }

    true
}

 

컴파일 하면 아래와 같이 에러가 납니다.

error[E0277]: the trait bound `std::string::String: std::ops::Index<usize>` is not satisfied
 --> <anon>:7:12
  |
7 |         if num_string[i] != num_string[(num_length - 1) - i] {
  |            ^^^^^^^^^^^^^
  |
  = note: the type `std::string::String` cannot be indexed by `usize`
  

즉, num_string[i] 와 같이 String의 indexing을 [i] 와 같이 

할 수가 없습니다. Rust 언어에서는!

 

그래서,

 

문제되는 이 코드를 

  num_string[i] 를 아래와 같이 변경해주어야 합니다.

let b: u8 = num_string.as_bytes()[i];
let c: char = b as char;// if you need to get the character as a unicode code point

 

이렇게

바꾸면,

 

다음 코드와 같이 변경하면됩니다.

fn is_palindrome(num: u64) -> bool {
    let num_string = num.to_string();
    let num_length = num_string.len();

    for i in 0 .. num_length / 2 {
    
        //let b: u8 = num_string.as_bytes()[i];
        //let c: char = b as char;

        if num_string.as_bytes()[i] as char != num_string.as_bytes()[(num_length - 1) - i] as char {
            return false;
        }
    }

    true
}

 

(추가)

그런데 이렇게 Rust에서는 String 인텍싱이 복잡(?)해진 이유는

C언어와 다르게 Rust는 String을 UTF-8포맷으로 저장하기 때문입니다.

이에 대한 자세한 언급은 하기 링크에서

  :=> doc.rust-lang.org/book/ch08-02-strings.html

  확인해 볼 수 있습니다.

 

즉, 다시말해서

"""

러스트는 기본적으로 utf8으로 문자열을 저장하기 때문에 일정한 길이의 byte단위로 나누는데 문제가 있습니다 만약 문자로만 iterate를 하고 싶다면 chars()를 쓰면 되고 단순히 byte array를 추출하고 싶으면 as_bytes()쓰면 됩니다 그래서 비교적(?) 복잡한 방식으로 메서드를 사용하는 겁니다

"""

 

예를들면,

  이렇게 테스트 해볼 수 있습니다.

 

그럼,

  공유합니다.

 

 

728x90