Rust:- RepeatChar Function

Background

Everyone has a todo list when learning a new language.

One of mine is the repeatChar function.

 

Code

Code – Function – RepeatChar


fn repeatChar(ch: char, n:usize) -> String
{
    return 
        
       (
            ch.to_string()
       ).repeat(n);
        
}

Code – Sample


/*
    Declare "Module" Constants
*/
const CHAR_EQUAL:char = '=';

/*
    Declare Function:- repeatChar
    
    Arguments:-
    
       a) ch: char
       b) length: usize
       
    return
        String
        
    "What it do?"
    
       a) Convert ch (char) to String
       b) repeats the resulting string n times
       
*/  
fn repeatChar(ch: char, n:usize) -> String
{
    return 
        
       (
            ch.to_string()
       ).repeat(n);
        
}


/*
    Function:- Main
*/
fn main() 
{
    
    /*
        Declare Variables
    */
    let header:&str;
    let marker:String;
    let length:usize;

    //get header
    header = "Book Store";
    
    //count number of characters
    // s.chars().count()
    length = header.chars().count();
    
    //get marker
    marker = repeatChar(CHAR_EQUAL, length);
    
    //display header
    println!(
                  "{0}"
                , header 
            );

    //display marker
    println!(
               "{0}"
              , marker
           );
    
}

Output

Image

Textual


Book Store
==========

Online Code Sharing

OnlineGDB

  1. rustCharRepeat
    Link

Source Code Control

GitLab

  1. rustString
    • rustStringRepeatChar.rs
      Link

References

  1. StackOverflow
    • How can I convert char to string?
      Link
    • Does Rust’s String have a method that returns the number of characters rather than the number of bytes?
      Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s