Build your own algorithm: split
The STL has a rich algorithm
library. Yet, on occasion you may find it missing something you need. One common need is a split
function.
A split
function splits a string on a character separator. For example, here's a Unix /etc/passwd
file from a standard Debian installation:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync
Each field is separated by a colon :
character, where the fields are:
- Login name
- Optional encrypted password
- User ID
- Group ID
- Username or comment
- Home directory
- Optional command interpreter
This is a standard file in POSIX-based operating systems, and there are others like it. Most scripting languages include a built-in function for splitting a string on a separator. There are simple ways to do this in C++. Still, std::string
is just another...