Strings are normally a built-in data type in most programming languages. String literals are hardcoded values (immutable in Rust) — they point to a specific location in the application binary.
String manipulation questions are commonly used for coding assessments, including online assessments and technical interviews, so it’s good to know how to work with them.
Basics
Strings are generally stored as ASCII values, where they’re encoded with an 8-bit unsigned integer value.
Language-specific
Rust
There are two main string “types” in Rust. One is the String
type, from the standard library. The other are str
string slices, which are references to encoded UTF-8 data stored elsewhere.
C++
In C++, std::string
is provided via the <string>
header file. Strings in this language benefit from several manipulation functions. More in the documentation.
Some notes:
- When we use the assignment operator
=
, we don’t copy the memory location the same way we do with C-style pointer strings. - We’re also able to do equality operations
==
,!=
.+
will concatenate, like higher-level languages. - To use any functions in
string.h
, we can include<cstring>
. We can convert to a C-style string with thec_str()
method. - Stringstreams are used to take user input via strings.
Useful methods:
c_str()
converts fromstd::string
to a C-style string.- Modifications:
push_back()
appends a character to the back of a string.pop_back()
deletes the last character.remove(index, num_chars)
removesnum_chars
characters starting at theindex
character.insert(index, substr)
inserts a specific substring at a given position.
And useful string manipulation functions:
- Checking category of character
int std::isdigit(int c)
: checks if . Returns Boolean.
C
There’s no formal string type in C. They’re instead represented and stored as char
arrays where the last index of the array stores the null character \0
. Any manipulation functions thus follow the same rules as arrays.
Additional string utilities are provided via the string.h header file.