rust string format code example

Example 1: java string format with placeholder

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

Example 2: python string format

print("My name is {0} and I am {1} years old".format(name, age))

Example 3: C++ string format ctime

#include <ctime>
#include <iostream>
using namespace std;

int main()
{
	time_t curr_time;
	tm * curr_tm;
	char date_string[100];
	char time_string[100];
	
	time(&curr_time);
	curr_tm = localtime(&curr_time);
	
	strftime(date_string, 50, "Today is %B %d, %Y", curr_tm);
	strftime(time_string, 50, "Current time is %T", curr_tm);
	
	cout << date_string << endl;
	cout << time_string << endl;
	
	return 0;
}

Example 4: rust format string

format!("Hello");                 // => "Hello"
format!("Hello, {}!", "world");   // => "Hello, world!"
format!("The number is {}", 1);   // => "The number is 1"
format!("{:?}", (3, 4));          // => "(3, 4)"
format!("{value}", value=4);      // => "4"
format!("{} {}", 1, 2);           // => "1 2"

Tags:

Rust Example