{

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


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

For example, if the given string is welcome, Output is Welcome.

Rust capitalizes first character of a string

Here is an example program to capitalize the case of a first character. In this example, Create a function capitalize_first_letter that takes a string argument and returns a string.

Inside a function, the first letter slice is extracted and converted to uppercase using to_uppercase next, takes a string slice except the first letter, Append these two strings using +

Here is an example 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..]
}

Output:

Welcome
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.