Chapter 5

Home

Strings and Characters

A 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.

What is a String?

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'

C++

#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;
}

Rust

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.

Reading a String from Input

Many problems give you a string on a line by itself. Here's how to read it.

C++

string s;
cin >> s;          // reads one word (stops at whitespace)
getline(cin, s);   // reads the whole line

Rust

let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
let s = s.trim();  // remove trailing newline

Problem: Count Vowels

Given a lowercase string, count how many vowels (a, e, i, o, u) it contains.

Sample input:
hello

Expected output:
2

C++

#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;
}

Rust

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);
}

Problem: Reverse a String

Sample input:
abcde

Expected output:
edcba

C++

string s; cin >> s;
reverse(s.begin(), s.end());
cout << s << "\n";

Rust

let s = "abcde";
let rev: String = s.chars().rev().collect();
println!("{}", rev);

Key Takeaways

Practice