How to capitalize the first letter of a string in Rust example

This tutorial demonstrates how to capitalize the first letter of a string.

For instance, if the given string is welcome, the output will be Welcome.

Capitalizing the First Character of a String in Rust

Below is an example program to capitalize the first character of a string.

In this example,

We create a function capitalize_first_letter that takes a string argument and returns a string.

Inside the function, we extract the first letter using slice syntax and convert it to uppercase using to_uppercase() method. Then, we take a string slice excluding the first letter and append these two strings using the + operator. Here’s the program.

fn main() {
    let name = "welcome";

    println!("{}", capitalize_first_letter(&name));
fn capitalize_first_letter(s: &str) -> String {
    s[0..1].to_uppercase() + &s[1..]