Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. String::chars() / bytes() / parse()

String::chars() / bytes() / parse()

Rust strings provide methods such as chars() (an iterator over Unicode characters), bytes() (an iterator over bytes), and parse() (converting a string to a numeric value). Case conversion is also supported as a built-in feature.

Syntax

let s = String::from("Hello, 世界");

// Returns an iterator over Unicode characters.
for c in s.chars() { /* ... */ }

// Returns an iterator over bytes.
for b in s.bytes() { /* ... */ }

// Converts a string to any type (the type must be specified).
let n: i32 = "42".parse().unwrap();
let f: f64 = "3.14".parse().unwrap();

// The return value of parse() is a Result type.
let result: Result<i32, _> = "abc".parse();
match result {
    Ok(n) => println!("Number: {}", n),
    Err(e) => println!("Conversion failed: {}", e),
}

// Case conversion.
let upper = s.to_uppercase();
let lower = s.to_lowercase();

Method List

MethodDescription
s.chars()Returns an iterator over Unicode characters (char).
s.char_indices()Returns an iterator of (byte offset, char) pairs.
s.bytes()Returns an iterator over UTF-8 bytes.
s.chars().count()Returns the number of Unicode characters.
s.chars().nth(n)Returns the nth char as Option<char>.
s.parse::<T>()Converts the string to type T and returns Result<T, E>.
s.to_uppercase()Returns a new String converted to uppercase.
s.to_lowercase()Returns a new String converted to lowercase.
s.to_ascii_uppercase()Converts only ASCII characters to uppercase.
s.to_ascii_lowercase()Converts only ASCII characters to lowercase.
s.chars().collect::<String>()Rebuilds a char iterator back into a String.

Sample Code

fn main() {
    let s = "Hello, 世界!";

    // Process each Unicode character one by one with chars().
    println!("--- chars() ---");
    println!("Char count: {}", s.chars().count());
    println!("Byte count: {}", s.len());

    let chars: Vec<char> = s.chars().collect();
    println!("chars[0]: {}", chars[0]);    // 'H'
    println!("chars[7]: {}", chars[7]);    // '世'

    // Get both the byte offset and the character at once with char_indices.
    println!("\n--- char_indices (first 5 characters) ---");
    for (i, c) in s.char_indices().take(5) {
        println!("  offset={}, char='{}'", i, c);
    }

    // Process raw bytes with bytes().
    println!("\n--- bytes (first 5 bytes) ---");
    let first5: Vec<u8> = s.bytes().take(5).collect();
    println!("  {:?}", first5);

    // Convert a string to a number with parse().
    println!("\n--- parse() ---");
    let n: i32 = "42".parse().unwrap();
    let f: f64 = "3.14".parse().unwrap();
    println!("i32: {}", n);
    println!("f64: {}", f);

    // parse() with error handling.
    let inputs = ["100", "-5", "abc", "3.14"];
    for input in inputs {
        match input.parse::<i32>() {
            Ok(n) => println!("  '{}'  => i32: {}", input, n),
            Err(e) => println!("  '{}'  => error: {}", input, e),
        }
    }

    // Case conversion.
    println!("\n--- uppercase / lowercase ---");
    let mixed = "Hello, World!";
    println!("to_uppercase: {}", mixed.to_uppercase());
    println!("to_lowercase: {}", mixed.to_lowercase());

    // Example of transforming each character using chars().
    let reversed: String = mixed.chars().rev().collect();
    println!("reversed: {}", reversed);

    let only_alpha: String = mixed.chars().filter(|c| c.is_alphabetic()).collect();
    println!("alphabetic only: {}", only_alpha);
}

Overview

chars() is the standard way to process a Rust string one character at a time. Because Rust's char type is a 4-byte Unicode scalar value, Japanese characters and emoji are each treated as a single character.

parse() converts a string by inferring or explicitly specifying the target type. Because the return value is a Result type, conversion failures can be handled safely. You specify the type either with turbofish syntax — "42".parse::<i32>() — or with a type annotation on the variable.

The iterator returned by chars() is O(n). Accessing the nth character with s.chars().nth(n) scans from the beginning, so it is not suitable for random access.

If you find any errors or copyright issues, please .