Chapter 5
HomeA string is really just an array of characters. Most CP problems that involve text — parsing input, checking palindromes, counting letters — are really array problems in disguise.
In C++, a string is a container of char values.
In Rust, a String is a growable UTF-8 buffer. You index into
them just like arrays.
📐 String as array of characters
String "hello": index: 0 1 2 3 4 char: 'h' 'e' 'l' 'l' 'o'
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "hello";
cout << s[0] << "\n"; // h
cout << s[4] << "\n"; // o
// length
cout << s.size() << "\n"; // 5
// modify
s[0] = 'j';
cout << s << "\n"; // jello
return 0;
}
fn main() {
let s = "hello";
// bytes (ASCII-safe for simple CP strings)
println!("{}", &s[0..1]); // h
println!("{}", &s[4..5]); // o
// length in bytes
println!("{}", s.len()); // 5
// iterate over characters
for c in s.chars() {
print!("{} ", c); // h e l l o
}
}
Rust strings are UTF-8. For CP ASCII input s[0..1] works fine.
Many problems give you a string on a line by itself. Here's how to read it.
string s; cin >> s; // reads one word (stops at whitespace) getline(cin, s); // reads the whole line
let mut s = String::new(); io::stdin().read_line(&mut s).unwrap(); let s = s.trim(); // remove trailing newline
Given a lowercase string, count how many vowels (a, e, i, o, u) it contains.
Sample input: hello Expected output: 2
#include <bits/stdc++.h>
using namespace std;
int main() {
string s; cin >> s;
int count = 0;
for (char c : s) {
if (c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u') {
count++;
}
}
cout << count << "\n";
return 0;
}
use std::io::{self, Read};
fn main() {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
let count = s
.trim()
.chars()
.filter(|&c| "aeiou".contains(c))
.count();
println!("{}", count);
}
Sample input: abcde Expected output: edcba
string s; cin >> s; reverse(s.begin(), s.end()); cout << s << "\n";
let s = "abcde";
let rev: String = s.chars().rev().collect();
println!("{}", rev);
string (C++) reads one word with cin >>, one line with getline.
.chars() to iterate, .len() for byte length.
reverse() (C++) and .rev() (Rust) reverse a string.