String manipulations
C++ :
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main ()
{
// string concatenation
string salute = "Hello";
string name = "world";
string greeting = salute + " " + name;
greeting += '!';
cout << greeting << endl;
// to upper
string str = greeting;
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;
// to lower
str = greeting;
transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << str << endl;
// string format
int a = 1;
int b = 2;
int c = a + b;
ostringstream os;
os << "The sum of " << a << " and " << b << " is " << c;
cout << os.str() << endl;
string s1 ("There are two objects on the table, the 1st object is a book, the 2nd object is a pen.");
string s2 ("object");
// get character at a position
char ch = s1[6];
cout << ch << endl;
// substring
string s3 = s1.substr(10, 11);
cout << s3 << endl;
// string replace
string s4 = s3.replace(0, 3, "three");
cout << s4 << endl;
// string find
size_t found = s1.find(s2);
if (found!=string::npos)
cout << "first 'object' found at: " << found << endl;
// string reverse find
found = s1.rfind(s2);
if (found!=string::npos)
cout << "last 'object' found at: " << found << endl;
return 0;
}
Rust :
fn main()
{
// string concatenation
let salute = "Hello";
let name = "world";
let mut greeting_string : String = salute.to_owned() + " " + name;
greeting_string.push('!');
let greeting :&str = &greeting_string;
println!("{}", greeting);
// upper case
println!("{}", greeting_string.to_uppercase());
// lower case
println!("{}", greeting_string.to_lowercase());
// string format
let a = 1;
let b = 2;
let c = a + b;
let tmp_string : String = format!("The sum of {} and {} is {}", a, b, c);
let s : &str = &tmp_string;
println!("{}", s);
let s1 = "There are two objects on the table, the 1st object is a book, the 2nd object is a pen.";
let s2 = "object";
// get character at a position
let ch = s1.chars().nth(6).unwrap();
println!("{}", ch);
// substring
let s3 = &s1.chars().skip(10).take(11).collect::<String>();
// For ascii string , you can use : let s3 = &s1[10..21];
println!("{}", s3);
// string replace
let s4 = str::replace(s3, "two", "three");
println!("{}", s4);
// string find
if let Some(found) = s1.find(s2)
{
println!("first 'object' found at: {}", found);
}
// string reverse find
if let Some(found) = s1.rfind(s2)
{
println!("last 'object' found at: {}", found);
}
}
As stated in chapter "Basic data types", Rust has two types of string : the raw string &str , and the object String.
The operator + only works for String and does not work for &str, therefore in order to concatenate several raw strings &str, we need to convert the first of them into an object String and then apply the + operator to the remained items.
To convert from &str to String :
let greeting_string : String = salute.to_owned()
To convert from String to &str :
let greeting :&str = &greeting_string;