rust
18 lines · 5 steps
Collapsing runs of whitespace in Rust
A single pass with a boolean flag squeezes any run of whitespace down to one space.
Explained by
highlit
1pub fn collapse_whitespace(input: &str) -> String {
2 let mut result = String::with_capacity(input.len());
3 let mut in_whitespace = false;
4
5 for ch in input.chars() {
6 if ch.is_whitespace() {
7 if !in_whitespace {
8 result.push(' ');
9 in_whitespace = true;
10 }
11 } else {
12 result.push(ch);
13 in_whitespace = false;
14 }
15 }
16
17 result.trim().to_string()
18}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single boolean flag turns a stream of characters into a tiny state machine that dedupes runs.
- 2Pre-sizing a String with with_capacity avoids repeated reallocation during the build.
- 3Deferring edge trimming to the end keeps the main loop simple and uniform.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/collapsing-runs-of-whitespace-in-rust-explained-rust-caaf/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.